]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/GenFds/GenFds.py
Enable EFI_BROWSER_ACTION_CHANGED callback type for browser.
[mirror_edk2.git] / BaseTools / Source / Python / GenFds / GenFds.py
CommitLineData
30fdf114
LG
1## @file
2# generate flash image
3#
40d841f6 4# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
30fdf114 5#
40d841f6 6# This program and the accompanying materials
30fdf114
LG
7# are licensed and made available under the terms and conditions of the BSD License
8# which accompanies this distribution. The full text of the license may be found at
9# http://opensource.org/licenses/bsd-license.php
10#
11# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
12# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
13#
14
15##
16# Import Modules
17#
18from optparse import OptionParser
19import sys
20import os
21import linecache
22import FdfParser
fd171542 23import Common.BuildToolError as BuildToolError
30fdf114
LG
24from GenFdsGlobalVariable import GenFdsGlobalVariable
25from Workspace.WorkspaceDatabase import WorkspaceDatabase
26from Workspace.BuildClassObject import PcdClassObject
27from Workspace.BuildClassObject import ModuleBuildClassObject
28import RuleComplexFile
29from EfiSection import EfiSection
30import StringIO
31import Common.TargetTxtClassObject as TargetTxtClassObject
32import Common.ToolDefClassObject as ToolDefClassObject
33import Common.DataType
34import Common.GlobalData as GlobalData
35from Common import EdkLogger
36from Common.String import *
37from Common.Misc import DirCache,PathClass
40d841f6 38from Common.Misc import SaveFileOnChange
b36d134f 39from Common.BuildVersion import gBUILD_VERSION
30fdf114
LG
40
41## Version and Copyright
b36d134f 42versionNumber = "1.0" + ' ' + gBUILD_VERSION
30fdf114 43__version__ = "%prog Version " + versionNumber
52302d4d 44__copyright__ = "Copyright (c) 2007 - 2010, Intel Corporation All rights reserved."
30fdf114
LG
45
46## Tool entrance method
47#
48# This method mainly dispatch specific methods per the command line options.
49# If no error found, return zero value so the caller of this tool can know
50# if it's executed successfully or not.
51#
52# @retval 0 Tool was successful
53# @retval 1 Tool failed
54#
55def main():
56 global Options
57 Options = myOptionParser()
58
59 global Workspace
60 Workspace = ""
61 ArchList = None
62 ReturnCode = 0
63
64 EdkLogger.Initialize()
65 try:
66 if Options.verbose != None:
67 EdkLogger.SetLevel(EdkLogger.VERBOSE)
68 GenFdsGlobalVariable.VerboseMode = True
69
70 if Options.FixedAddress != None:
71 GenFdsGlobalVariable.FixedLoadAddress = True
72
73 if Options.quiet != None:
74 EdkLogger.SetLevel(EdkLogger.QUIET)
75 if Options.debug != None:
76 EdkLogger.SetLevel(Options.debug + 1)
77 GenFdsGlobalVariable.DebugLevel = Options.debug
78 else:
79 EdkLogger.SetLevel(EdkLogger.INFO)
80
81 if (Options.Workspace == None):
fd171542 82 EdkLogger.error("GenFds", OPTION_MISSING, "WORKSPACE not defined",
30fdf114
LG
83 ExtraData="Please use '-w' switch to pass it or set the WORKSPACE environment variable.")
84 elif not os.path.exists(Options.Workspace):
fd171542 85 EdkLogger.error("GenFds", PARAMETER_INVALID, "WORKSPACE is invalid",
30fdf114
LG
86 ExtraData="Please use '-w' switch to pass it or set the WORKSPACE environment variable.")
87 else:
88 Workspace = os.path.normcase(Options.Workspace)
89 GenFdsGlobalVariable.WorkSpaceDir = Workspace
90 if 'EDK_SOURCE' in os.environ.keys():
91 GenFdsGlobalVariable.EdkSourceDir = os.path.normcase(os.environ['EDK_SOURCE'])
92 if (Options.debug):
93 GenFdsGlobalVariable.VerboseLogger( "Using Workspace:" + Workspace)
94 os.chdir(GenFdsGlobalVariable.WorkSpaceDir)
95
96 if (Options.filename):
97 FdfFilename = Options.filename
98 FdfFilename = GenFdsGlobalVariable.ReplaceWorkspaceMacro(FdfFilename)
52302d4d
LG
99
100 if FdfFilename[0:2] == '..':
101 FdfFilename = os.path.realpath(FdfFilename)
102 if not os.path.isabs (FdfFilename):
103 FdfFilename = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, FdfFilename)
104 if not os.path.exists(FdfFilename):
105 EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=FdfFilename)
106 if os.path.normcase (FdfFilename).find(Workspace) != 0:
107 EdkLogger.error("GenFds", FILE_NOT_FOUND, "FdfFile doesn't exist in Workspace!")
108
109 GenFdsGlobalVariable.FdfFile = FdfFilename
110 GenFdsGlobalVariable.FdfFileTimeStamp = os.path.getmtime(FdfFilename)
30fdf114 111 else:
fd171542 112 EdkLogger.error("GenFds", OPTION_MISSING, "Missing FDF filename")
30fdf114
LG
113
114 if (Options.BuildTarget):
115 GenFdsGlobalVariable.TargetName = Options.BuildTarget
116 else:
fd171542 117 EdkLogger.error("GenFds", OPTION_MISSING, "Missing build target")
30fdf114
LG
118
119 if (Options.ToolChain):
120 GenFdsGlobalVariable.ToolChainTag = Options.ToolChain
121 else:
fd171542 122 EdkLogger.error("GenFds", OPTION_MISSING, "Missing tool chain tag")
30fdf114 123
30fdf114
LG
124 if (Options.activePlatform):
125 ActivePlatform = Options.activePlatform
126 ActivePlatform = GenFdsGlobalVariable.ReplaceWorkspaceMacro(ActivePlatform)
127
128 if ActivePlatform[0:2] == '..':
129 ActivePlatform = os.path.realpath(ActivePlatform)
130
52302d4d 131 if not os.path.isabs (ActivePlatform):
30fdf114
LG
132 ActivePlatform = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, ActivePlatform)
133
134 if not os.path.exists(ActivePlatform) :
fd171542 135 EdkLogger.error("GenFds", FILE_NOT_FOUND, "ActivePlatform doesn't exist!")
30fdf114 136
52302d4d 137 if os.path.normcase (ActivePlatform).find(Workspace) != 0:
fd171542 138 EdkLogger.error("GenFds", FILE_NOT_FOUND, "ActivePlatform doesn't exist in Workspace!")
30fdf114 139
52302d4d 140 ActivePlatform = ActivePlatform[len(Workspace):]
30fdf114
LG
141 if len(ActivePlatform) > 0 :
142 if ActivePlatform[0] == '\\' or ActivePlatform[0] == '/':
143 ActivePlatform = ActivePlatform[1:]
144 else:
fd171542 145 EdkLogger.error("GenFds", FILE_NOT_FOUND, "ActivePlatform doesn't exist!")
52302d4d 146 else:
fd171542 147 EdkLogger.error("GenFds", OPTION_MISSING, "Missing active platform")
30fdf114
LG
148
149 GenFdsGlobalVariable.ActivePlatform = PathClass(NormPath(ActivePlatform), Workspace)
150
151 BuildConfigurationFile = os.path.normpath(os.path.join(GenFdsGlobalVariable.WorkSpaceDir, "Conf/target.txt"))
152 if os.path.isfile(BuildConfigurationFile) == True:
153 TargetTxtClassObject.TargetTxtClassObject(BuildConfigurationFile)
154 else:
fd171542 155 EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=BuildConfigurationFile)
30fdf114
LG
156
157 if Options.Macros:
158 for Pair in Options.Macros:
159 Pair.strip('"')
160 List = Pair.split('=')
161 if len(List) == 2:
30fdf114
LG
162 if List[0].strip() == "EFI_SOURCE":
163 GlobalData.gEfiSource = List[1].strip()
0d2711a6 164 GlobalData.gGlobalDefines["EFI_SOURCE"] = GlobalData.gEfiSource
fd171542 165 continue
30fdf114
LG
166 elif List[0].strip() == "EDK_SOURCE":
167 GlobalData.gEdkSource = List[1].strip()
0d2711a6 168 GlobalData.gGlobalDefines["EDK_SOURCE"] = GlobalData.gEdkSource
fd171542 169 continue
0d2711a6
LG
170 elif List[0].strip() in ["WORKSPACE", "TARGET", "TOOLCHAIN"]:
171 GlobalData.gGlobalDefines[List[0].strip()] = List[1].strip()
30fdf114 172 else:
0d2711a6 173 GlobalData.gCommandLineDefines[List[0].strip()] = List[1].strip()
30fdf114 174 else:
0d2711a6
LG
175 GlobalData.gCommandLineDefines[List[0].strip()] = "TRUE"
176 os.environ["WORKSPACE"] = Workspace
30fdf114
LG
177
178 """call Workspace build create database"""
0d2711a6 179 BuildWorkSpace = WorkspaceDatabase(None)
30fdf114
LG
180 BuildWorkSpace.InitDatabase()
181
182 #
183 # Get files real name in workspace dir
184 #
185 GlobalData.gAllFiles = DirCache(Workspace)
186 GlobalData.gWorkspace = Workspace
187
188 if (Options.archList) :
189 ArchList = Options.archList.split(',')
190 else:
fd171542 191# EdkLogger.error("GenFds", OPTION_MISSING, "Missing build ARCH")
0d2711a6 192 ArchList = BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, 'COMMON', Options.BuildTarget, Options.ToolChain].SupArchList
30fdf114 193
0d2711a6 194 TargetArchList = set(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, 'COMMON', Options.BuildTarget, Options.ToolChain].SupArchList) & set(ArchList)
30fdf114
LG
195 if len(TargetArchList) == 0:
196 EdkLogger.error("GenFds", GENFDS_ERROR, "Target ARCH %s not in platform supported ARCH %s" % (str(ArchList), str(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, 'COMMON'].SupArchList)))
197
198 for Arch in ArchList:
0d2711a6
LG
199 GenFdsGlobalVariable.OutputDirFromDscDict[Arch] = NormPath(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, Options.BuildTarget, Options.ToolChain].OutputDirectory)
200 GenFdsGlobalVariable.PlatformName = BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, Options.BuildTarget, Options.ToolChain].PlatformName
30fdf114
LG
201
202 if (Options.outputDir):
203 OutputDirFromCommandLine = GenFdsGlobalVariable.ReplaceWorkspaceMacro(Options.outputDir)
d5d56f1b
LG
204 if not os.path.isabs (OutputDirFromCommandLine):
205 OutputDirFromCommandLine = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, OutputDirFromCommandLine)
30fdf114
LG
206 for Arch in ArchList:
207 GenFdsGlobalVariable.OutputDirDict[Arch] = OutputDirFromCommandLine
208 else:
209 for Arch in ArchList:
210 GenFdsGlobalVariable.OutputDirDict[Arch] = os.path.join(GenFdsGlobalVariable.OutputDirFromDscDict[Arch], GenFdsGlobalVariable.TargetName + '_' + GenFdsGlobalVariable.ToolChainTag)
211
212 for Key in GenFdsGlobalVariable.OutputDirDict:
213 OutputDir = GenFdsGlobalVariable.OutputDirDict[Key]
214 if OutputDir[0:2] == '..':
215 OutputDir = os.path.realpath(OutputDir)
216
217 if OutputDir[1] != ':':
218 OutputDir = os.path.join (GenFdsGlobalVariable.WorkSpaceDir, OutputDir)
219
220 if not os.path.exists(OutputDir):
fd171542 221 EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=OutputDir)
30fdf114
LG
222 GenFdsGlobalVariable.OutputDirDict[Key] = OutputDir
223
224 """ Parse Fdf file, has to place after build Workspace as FDF may contain macros from DSC file """
225 FdfParserObj = FdfParser.FdfParser(FdfFilename)
226 FdfParserObj.ParseFile()
227
228 if FdfParserObj.CycleReferenceCheck():
fd171542 229 EdkLogger.error("GenFds", FORMAT_NOT_SUPPORTED, "Cycle Reference Detected in FDF file")
30fdf114
LG
230
231 if (Options.uiFdName) :
232 if Options.uiFdName.upper() in FdfParserObj.Profile.FdDict.keys():
233 GenFds.OnlyGenerateThisFd = Options.uiFdName
234 else:
fd171542 235 EdkLogger.error("GenFds", OPTION_VALUE_INVALID,
30fdf114
LG
236 "No such an FD in FDF file: %s" % Options.uiFdName)
237
238 if (Options.uiFvName) :
239 if Options.uiFvName.upper() in FdfParserObj.Profile.FvDict.keys():
240 GenFds.OnlyGenerateThisFv = Options.uiFvName
241 else:
fd171542 242 EdkLogger.error("GenFds", OPTION_VALUE_INVALID,
30fdf114
LG
243 "No such an FV in FDF file: %s" % Options.uiFvName)
244
4234283c
LG
245 if (Options.uiCapName) :
246 if Options.uiCapName.upper() in FdfParserObj.Profile.CapsuleDict.keys():
247 GenFds.OnlyGenerateThisCap = Options.uiCapName
248 else:
249 EdkLogger.error("GenFds", OPTION_VALUE_INVALID,
250 "No such a Capsule in FDF file: %s" % Options.uiCapName)
251
30fdf114
LG
252 """Modify images from build output if the feature of loading driver at fixed address is on."""
253 if GenFdsGlobalVariable.FixedLoadAddress:
254 GenFds.PreprocessImage(BuildWorkSpace, GenFdsGlobalVariable.ActivePlatform)
255 """Call GenFds"""
256 GenFds.GenFd('', FdfParserObj, BuildWorkSpace, ArchList)
52302d4d
LG
257
258 """Generate GUID cross reference file"""
259 GenFds.GenerateGuidXRefFile(BuildWorkSpace, ArchList)
260
30fdf114
LG
261 """Display FV space info."""
262 GenFds.DisplayFvSpaceInfo(FdfParserObj)
52302d4d 263
30fdf114 264 except FdfParser.Warning, X:
fd171542 265 EdkLogger.error(X.ToolName, FORMAT_INVALID, File=X.FileName, Line=X.LineNumber, ExtraData=X.Message, RaiseError = False)
266 ReturnCode = FORMAT_INVALID
30fdf114
LG
267 except FatalError, X:
268 if Options.debug != None:
269 import traceback
270 EdkLogger.quiet(traceback.format_exc())
271 ReturnCode = X.args[0]
272 except:
273 import traceback
274 EdkLogger.error(
275 "\nPython",
276 CODE_ERROR,
277 "Tools code failure",
f3decdc3 278 ExtraData="Please send email to edk2-buildtools-devel@lists.sourceforge.net for help, attaching following call stack trace!\n",
30fdf114
LG
279 RaiseError=False
280 )
0d2711a6
LG
281 if Options.debug != None:
282 EdkLogger.quiet(traceback.format_exc())
30fdf114
LG
283 ReturnCode = CODE_ERROR
284 return ReturnCode
285
286gParamCheck = []
287def SingleCheckCallback(option, opt_str, value, parser):
288 if option not in gParamCheck:
289 setattr(parser.values, option.dest, value)
290 gParamCheck.append(option)
291 else:
292 parser.error("Option %s only allows one instance in command line!" % option)
293
294## Parse command line options
295#
296# Using standard Python module optparse to parse command line option of this tool.
297#
298# @retval Opt A optparse.Values object containing the parsed options
299# @retval Args Target of build command
300#
301def myOptionParser():
302 usage = "%prog [options] -f input_file -a arch_list -b build_target -p active_platform -t tool_chain_tag -D \"MacroName [= MacroValue]\""
303 Parser = OptionParser(usage=usage,description=__copyright__,version="%prog " + str(versionNumber))
304 Parser.add_option("-f", "--file", dest="filename", type="string", help="Name of FDF file to convert", action="callback", callback=SingleCheckCallback)
305 Parser.add_option("-a", "--arch", dest="archList", help="comma separated list containing one or more of: IA32, X64, IPF, ARM or EBC which should be built, overrides target.txt?s TARGET_ARCH")
306 Parser.add_option("-q", "--quiet", action="store_true", type=None, help="Disable all messages except FATAL ERRORS.")
307 Parser.add_option("-v", "--verbose", action="store_true", type=None, help="Turn on verbose output with informational messages printed.")
308 Parser.add_option("-d", "--debug", action="store", type="int", help="Enable debug messages at specified level.")
309 Parser.add_option("-p", "--platform", type="string", dest="activePlatform", help="Set the ACTIVE_PLATFORM, overrides target.txt ACTIVE_PLATFORM setting.",
310 action="callback", callback=SingleCheckCallback)
311 Parser.add_option("-w", "--workspace", type="string", dest="Workspace", default=os.environ.get('WORKSPACE'), help="Set the WORKSPACE",
312 action="callback", callback=SingleCheckCallback)
313 Parser.add_option("-o", "--outputDir", type="string", dest="outputDir", help="Name of Build Output directory",
314 action="callback", callback=SingleCheckCallback)
315 Parser.add_option("-r", "--rom_image", dest="uiFdName", help="Build the image using the [FD] section named by FdUiName.")
4234283c
LG
316 Parser.add_option("-i", "--FvImage", dest="uiFvName", help="Build the FV image using the [FV] section named by UiFvName")
317 Parser.add_option("-C", "--CapsuleImage", dest="uiCapName", help="Build the Capsule image using the [Capsule] section named by UiCapName")
b36d134f 318 Parser.add_option("-b", "--buildtarget", type="choice", choices=['DEBUG','RELEASE', 'NOOPT'], dest="BuildTarget", help="Build TARGET is one of list: DEBUG, RELEASE, NOOPT.",
30fdf114
LG
319 action="callback", callback=SingleCheckCallback)
320 Parser.add_option("-t", "--tagname", type="string", dest="ToolChain", help="Using the tools: TOOL_CHAIN_TAG name to build the platform.",
321 action="callback", callback=SingleCheckCallback)
322 Parser.add_option("-D", "--define", action="append", type="string", dest="Macros", help="Macro: \"Name [= Value]\".")
323 Parser.add_option("-s", "--specifyaddress", dest="FixedAddress", action="store_true", type=None, help="Specify driver load address.")
324 (Options, args) = Parser.parse_args()
325 return Options
326
327## The class implementing the EDK2 flash image generation process
328#
329# This process includes:
330# 1. Collect workspace information, includes platform and module information
331# 2. Call methods of Fd class to generate FD
332# 3. Call methods of Fv class to generate FV that not belong to FD
333#
334class GenFds :
335 FdfParsef = None
fd171542 336 # FvName, FdName, CapName in FDF, Image file name
337 ImageBinDict = {}
30fdf114
LG
338 OnlyGenerateThisFd = None
339 OnlyGenerateThisFv = None
4234283c 340 OnlyGenerateThisCap = None
30fdf114
LG
341
342 ## GenFd()
343 #
344 # @param OutputDir Output directory
345 # @param FdfParser FDF contents parser
346 # @param Workspace The directory of workspace
347 # @param ArchList The Arch list of platform
348 #
349 def GenFd (OutputDir, FdfParser, WorkSpace, ArchList):
350 GenFdsGlobalVariable.SetDir ('', FdfParser, WorkSpace, ArchList)
351
fd171542 352 GenFdsGlobalVariable.VerboseLogger(" Generate all Fd images and their required FV and Capsule images!")
4234283c
LG
353 if GenFds.OnlyGenerateThisCap != None and GenFds.OnlyGenerateThisCap.upper() in GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict.keys():
354 CapsuleObj = GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict.get(GenFds.OnlyGenerateThisCap.upper())
355 if CapsuleObj != None:
356 CapsuleObj.GenCapsule()
357 return
358
30fdf114
LG
359 if GenFds.OnlyGenerateThisFd != None and GenFds.OnlyGenerateThisFd.upper() in GenFdsGlobalVariable.FdfParser.Profile.FdDict.keys():
360 FdObj = GenFdsGlobalVariable.FdfParser.Profile.FdDict.get(GenFds.OnlyGenerateThisFd.upper())
361 if FdObj != None:
fd171542 362 FdObj.GenFd()
4234283c
LG
363 return
364 elif GenFds.OnlyGenerateThisFd == None and GenFds.OnlyGenerateThisFv == None:
30fdf114
LG
365 for FdName in GenFdsGlobalVariable.FdfParser.Profile.FdDict.keys():
366 FdObj = GenFdsGlobalVariable.FdfParser.Profile.FdDict[FdName]
fd171542 367 FdObj.GenFd()
30fdf114 368
fd171542 369 GenFdsGlobalVariable.VerboseLogger("\n Generate other FV images! ")
30fdf114
LG
370 if GenFds.OnlyGenerateThisFv != None and GenFds.OnlyGenerateThisFv.upper() in GenFdsGlobalVariable.FdfParser.Profile.FvDict.keys():
371 FvObj = GenFdsGlobalVariable.FdfParser.Profile.FvDict.get(GenFds.OnlyGenerateThisFv.upper())
372 if FvObj != None:
373 Buffer = StringIO.StringIO()
6780eef1 374 FvObj.AddToBuffer(Buffer)
30fdf114
LG
375 Buffer.close()
376 return
fd171542 377 elif GenFds.OnlyGenerateThisFv == None:
30fdf114
LG
378 for FvName in GenFdsGlobalVariable.FdfParser.Profile.FvDict.keys():
379 Buffer = StringIO.StringIO('')
380 FvObj = GenFdsGlobalVariable.FdfParser.Profile.FvDict[FvName]
6780eef1 381 FvObj.AddToBuffer(Buffer)
30fdf114 382 Buffer.close()
52302d4d 383
4234283c 384 if GenFds.OnlyGenerateThisFv == None and GenFds.OnlyGenerateThisFd == None and GenFds.OnlyGenerateThisCap == None:
fd171542 385 if GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict != {}:
386 GenFdsGlobalVariable.VerboseLogger("\n Generate other Capsule images!")
387 for CapsuleName in GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict.keys():
388 CapsuleObj = GenFdsGlobalVariable.FdfParser.Profile.CapsuleDict[CapsuleName]
389 CapsuleObj.GenCapsule()
390
30fdf114 391 if GenFdsGlobalVariable.FdfParser.Profile.OptRomDict != {}:
fd171542 392 GenFdsGlobalVariable.VerboseLogger("\n Generate all Option ROM!")
30fdf114
LG
393 for DriverName in GenFdsGlobalVariable.FdfParser.Profile.OptRomDict.keys():
394 OptRomObj = GenFdsGlobalVariable.FdfParser.Profile.OptRomDict[DriverName]
395 OptRomObj.AddToBuffer(None)
396
397 ## GetFvBlockSize()
398 #
399 # @param FvObj Whose block size to get
400 # @retval int Block size value
401 #
402 def GetFvBlockSize(FvObj):
52302d4d 403 DefaultBlockSize = 0x1
30fdf114
LG
404 FdObj = None
405 if GenFds.OnlyGenerateThisFd != None and GenFds.OnlyGenerateThisFd.upper() in GenFdsGlobalVariable.FdfParser.Profile.FdDict.keys():
406 FdObj = GenFdsGlobalVariable.FdfParser.Profile.FdDict[GenFds.OnlyGenerateThisFd.upper()]
407 if FdObj == None:
408 for ElementFd in GenFdsGlobalVariable.FdfParser.Profile.FdDict.values():
409 for ElementRegion in ElementFd.RegionList:
410 if ElementRegion.RegionType == 'FV':
411 for ElementRegionData in ElementRegion.RegionDataList:
412 if ElementRegionData != None and ElementRegionData.upper() == FvObj.UiFvName:
413 if FvObj.BlockSizeList != []:
414 return FvObj.BlockSizeList[0][0]
415 else:
416 return ElementRegion.BlockSizeOfRegion(ElementFd.BlockSizeList)
417 if FvObj.BlockSizeList != []:
418 return FvObj.BlockSizeList[0][0]
419 return DefaultBlockSize
420 else:
421 for ElementRegion in FdObj.RegionList:
422 if ElementRegion.RegionType == 'FV':
423 for ElementRegionData in ElementRegion.RegionDataList:
424 if ElementRegionData != None and ElementRegionData.upper() == FvObj.UiFvName:
425 if FvObj.BlockSizeList != []:
426 return FvObj.BlockSizeList[0][0]
427 else:
428 return ElementRegion.BlockSizeOfRegion(ElementFd.BlockSizeList)
429 return DefaultBlockSize
430
431 ## DisplayFvSpaceInfo()
432 #
433 # @param FvObj Whose block size to get
434 # @retval None
435 #
436 def DisplayFvSpaceInfo(FdfParser):
437
438 FvSpaceInfoList = []
439 MaxFvNameLength = 0
440 for FvName in FdfParser.Profile.FvDict:
441 if len(FvName) > MaxFvNameLength:
442 MaxFvNameLength = len(FvName)
443 FvSpaceInfoFileName = os.path.join(GenFdsGlobalVariable.FvDir, FvName.upper() + '.Fv.map')
444 if os.path.exists(FvSpaceInfoFileName):
445 FileLinesList = linecache.getlines(FvSpaceInfoFileName)
446 TotalFound = False
447 Total = ''
448 UsedFound = False
449 Used = ''
450 FreeFound = False
451 Free = ''
452 for Line in FileLinesList:
453 NameValue = Line.split('=')
454 if len(NameValue) == 2:
455 if NameValue[0].strip() == 'EFI_FV_TOTAL_SIZE':
456 TotalFound = True
457 Total = NameValue[1].strip()
458 if NameValue[0].strip() == 'EFI_FV_TAKEN_SIZE':
459 UsedFound = True
460 Used = NameValue[1].strip()
461 if NameValue[0].strip() == 'EFI_FV_SPACE_SIZE':
462 FreeFound = True
463 Free = NameValue[1].strip()
464
465 if TotalFound and UsedFound and FreeFound:
466 FvSpaceInfoList.append((FvName, Total, Used, Free))
467
468 GenFdsGlobalVariable.InfLogger('\nFV Space Information')
469 for FvSpaceInfo in FvSpaceInfoList:
470 Name = FvSpaceInfo[0]
471 TotalSizeValue = long(FvSpaceInfo[1], 0)
472 UsedSizeValue = long(FvSpaceInfo[2], 0)
473 FreeSizeValue = long(FvSpaceInfo[3], 0)
6780eef1
LG
474 if UsedSizeValue == TotalSizeValue:
475 Percentage = '100'
476 else:
477 Percentage = str((UsedSizeValue+0.0)/TotalSizeValue)[0:4].lstrip('0.')
478
479 GenFdsGlobalVariable.InfLogger(Name + ' ' + '[' + Percentage + '%Full] ' + str(TotalSizeValue) + ' total, ' + str(UsedSizeValue) + ' used, ' + str(FreeSizeValue) + ' free')
30fdf114
LG
480
481 ## PreprocessImage()
482 #
483 # @param BuildDb Database from build meta data files
484 # @param DscFile modules from dsc file will be preprocessed
485 # @retval None
486 #
487 def PreprocessImage(BuildDb, DscFile):
0d2711a6 488 PcdDict = BuildDb.BuildObject[DscFile, 'COMMON', GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].Pcds
30fdf114
LG
489 PcdValue = ''
490 for Key in PcdDict:
491 PcdObj = PcdDict[Key]
492 if PcdObj.TokenCName == 'PcdBsBaseAddress':
493 PcdValue = PcdObj.DefaultValue
494 break
495
496 if PcdValue == '':
497 return
498
499 Int64PcdValue = long(PcdValue, 0)
500 if Int64PcdValue == 0 or Int64PcdValue < -1:
501 return
502
503 TopAddress = 0
504 if Int64PcdValue > 0:
505 TopAddress = Int64PcdValue
506
0d2711a6 507 ModuleDict = BuildDb.BuildObject[DscFile, 'COMMON', GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].Modules
30fdf114 508 for Key in ModuleDict:
0d2711a6 509 ModuleObj = BuildDb.BuildObject[Key, 'COMMON', GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag]
30fdf114
LG
510 print ModuleObj.BaseName + ' ' + ModuleObj.ModuleType
511
52302d4d
LG
512 def GenerateGuidXRefFile(BuildDb, ArchList):
513 GuidXRefFileName = os.path.join(GenFdsGlobalVariable.FvDir, "Guid.xref")
40d841f6 514 GuidXRefFile = StringIO.StringIO('')
52302d4d 515 for Arch in ArchList:
0d2711a6 516 PlatformDataBase = BuildDb.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag]
52302d4d 517 for ModuleFile in PlatformDataBase.Modules:
0d2711a6 518 Module = BuildDb.BuildObject[ModuleFile, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag]
52302d4d 519 GuidXRefFile.write("%s %s\n" % (Module.Guid, Module.BaseName))
0d2711a6 520 SaveFileOnChange(GuidXRefFileName, GuidXRefFile.getvalue(), False)
52302d4d 521 GuidXRefFile.close()
40d841f6 522 GenFdsGlobalVariable.InfLogger("\nGUID cross reference file can be found at %s" % GuidXRefFileName)
52302d4d 523
30fdf114
LG
524 ##Define GenFd as static function
525 GenFd = staticmethod(GenFd)
526 GetFvBlockSize = staticmethod(GetFvBlockSize)
527 DisplayFvSpaceInfo = staticmethod(DisplayFvSpaceInfo)
528 PreprocessImage = staticmethod(PreprocessImage)
52302d4d 529 GenerateGuidXRefFile = staticmethod(GenerateGuidXRefFile)
30fdf114
LG
530
531if __name__ == '__main__':
532 r = main()
533 ## 0-127 is a safe return range, and 1 is a standard default error
534 if r < 0 or r > 127: r = 1
535 sys.exit(r)
536