]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/GenFds/GenFds.py
Sync BaseTool trunk (version r2670) into EDKII BaseTools.
[mirror_edk2.git] / BaseTools / Source / Python / GenFds / GenFds.py
1 ## @file
2 # generate flash image
3 #
4 # Copyright (c) 2007 - 2013, Intel Corporation. All rights reserved.<BR>
5 #
6 # This program and the accompanying materials
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 #
18 from optparse import OptionParser
19 import sys
20 import os
21 import linecache
22 import FdfParser
23 import Common.BuildToolError as BuildToolError
24 from GenFdsGlobalVariable import GenFdsGlobalVariable
25 from Workspace.WorkspaceDatabase import WorkspaceDatabase
26 from Workspace.BuildClassObject import PcdClassObject
27 from Workspace.BuildClassObject import ModuleBuildClassObject
28 import RuleComplexFile
29 from EfiSection import EfiSection
30 import StringIO
31 import Common.TargetTxtClassObject as TargetTxtClassObject
32 import Common.ToolDefClassObject as ToolDefClassObject
33 import Common.DataType
34 import Common.GlobalData as GlobalData
35 from Common import EdkLogger
36 from Common.String import *
37 from Common.Misc import DirCache,PathClass
38 from Common.Misc import SaveFileOnChange
39 from Common.Misc import GuidStructureStringToGuidString
40 from Common.BuildVersion import gBUILD_VERSION
41
42 ## Version and Copyright
43 versionNumber = "1.0" + ' ' + gBUILD_VERSION
44 __version__ = "%prog Version " + versionNumber
45 __copyright__ = "Copyright (c) 2007 - 2013, Intel Corporation All rights reserved."
46
47 ## Tool entrance method
48 #
49 # This method mainly dispatch specific methods per the command line options.
50 # If no error found, return zero value so the caller of this tool can know
51 # if it's executed successfully or not.
52 #
53 # @retval 0 Tool was successful
54 # @retval 1 Tool failed
55 #
56 def main():
57 global Options
58 Options = myOptionParser()
59
60 global Workspace
61 Workspace = ""
62 ArchList = None
63 ReturnCode = 0
64
65 EdkLogger.Initialize()
66 try:
67 if Options.verbose != None:
68 EdkLogger.SetLevel(EdkLogger.VERBOSE)
69 GenFdsGlobalVariable.VerboseMode = True
70
71 if Options.FixedAddress != None:
72 GenFdsGlobalVariable.FixedLoadAddress = True
73
74 if Options.quiet != None:
75 EdkLogger.SetLevel(EdkLogger.QUIET)
76 if Options.debug != None:
77 EdkLogger.SetLevel(Options.debug + 1)
78 GenFdsGlobalVariable.DebugLevel = Options.debug
79 else:
80 EdkLogger.SetLevel(EdkLogger.INFO)
81
82 if (Options.Workspace == None):
83 EdkLogger.error("GenFds", OPTION_MISSING, "WORKSPACE not defined",
84 ExtraData="Please use '-w' switch to pass it or set the WORKSPACE environment variable.")
85 elif not os.path.exists(Options.Workspace):
86 EdkLogger.error("GenFds", PARAMETER_INVALID, "WORKSPACE is invalid",
87 ExtraData="Please use '-w' switch to pass it or set the WORKSPACE environment variable.")
88 else:
89 Workspace = os.path.normcase(Options.Workspace)
90 GenFdsGlobalVariable.WorkSpaceDir = Workspace
91 if 'EDK_SOURCE' in os.environ.keys():
92 GenFdsGlobalVariable.EdkSourceDir = os.path.normcase(os.environ['EDK_SOURCE'])
93 if (Options.debug):
94 GenFdsGlobalVariable.VerboseLogger( "Using Workspace:" + Workspace)
95 os.chdir(GenFdsGlobalVariable.WorkSpaceDir)
96
97 if (Options.filename):
98 FdfFilename = Options.filename
99 FdfFilename = GenFdsGlobalVariable.ReplaceWorkspaceMacro(FdfFilename)
100
101 if FdfFilename[0:2] == '..':
102 FdfFilename = os.path.realpath(FdfFilename)
103 if not os.path.isabs (FdfFilename):
104 FdfFilename = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, FdfFilename)
105 if not os.path.exists(FdfFilename):
106 EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=FdfFilename)
107 if os.path.normcase (FdfFilename).find(Workspace) != 0:
108 EdkLogger.error("GenFds", FILE_NOT_FOUND, "FdfFile doesn't exist in Workspace!")
109
110 GenFdsGlobalVariable.FdfFile = FdfFilename
111 GenFdsGlobalVariable.FdfFileTimeStamp = os.path.getmtime(FdfFilename)
112 else:
113 EdkLogger.error("GenFds", OPTION_MISSING, "Missing FDF filename")
114
115 if (Options.BuildTarget):
116 GenFdsGlobalVariable.TargetName = Options.BuildTarget
117 else:
118 EdkLogger.error("GenFds", OPTION_MISSING, "Missing build target")
119
120 if (Options.ToolChain):
121 GenFdsGlobalVariable.ToolChainTag = Options.ToolChain
122 else:
123 EdkLogger.error("GenFds", OPTION_MISSING, "Missing tool chain tag")
124
125 if (Options.activePlatform):
126 ActivePlatform = Options.activePlatform
127 ActivePlatform = GenFdsGlobalVariable.ReplaceWorkspaceMacro(ActivePlatform)
128
129 if ActivePlatform[0:2] == '..':
130 ActivePlatform = os.path.realpath(ActivePlatform)
131
132 if not os.path.isabs (ActivePlatform):
133 ActivePlatform = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, ActivePlatform)
134
135 if not os.path.exists(ActivePlatform) :
136 EdkLogger.error("GenFds", FILE_NOT_FOUND, "ActivePlatform doesn't exist!")
137
138 if os.path.normcase (ActivePlatform).find(Workspace) != 0:
139 EdkLogger.error("GenFds", FILE_NOT_FOUND, "ActivePlatform doesn't exist in Workspace!")
140
141 ActivePlatform = ActivePlatform[len(Workspace):]
142 if len(ActivePlatform) > 0 :
143 if ActivePlatform[0] == '\\' or ActivePlatform[0] == '/':
144 ActivePlatform = ActivePlatform[1:]
145 else:
146 EdkLogger.error("GenFds", FILE_NOT_FOUND, "ActivePlatform doesn't exist!")
147 else:
148 EdkLogger.error("GenFds", OPTION_MISSING, "Missing active platform")
149
150 GenFdsGlobalVariable.ActivePlatform = PathClass(NormPath(ActivePlatform), Workspace)
151
152 BuildConfigurationFile = os.path.normpath(os.path.join(GenFdsGlobalVariable.WorkSpaceDir, "Conf/target.txt"))
153 if os.path.isfile(BuildConfigurationFile) == True:
154 TargetTxtClassObject.TargetTxtClassObject(BuildConfigurationFile)
155 else:
156 EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=BuildConfigurationFile)
157
158 if Options.Macros:
159 for Pair in Options.Macros:
160 Pair.strip('"')
161 List = Pair.split('=')
162 if len(List) == 2:
163 if List[0].strip() == "EFI_SOURCE":
164 GlobalData.gEfiSource = List[1].strip()
165 GlobalData.gGlobalDefines["EFI_SOURCE"] = GlobalData.gEfiSource
166 continue
167 elif List[0].strip() == "EDK_SOURCE":
168 GlobalData.gEdkSource = List[1].strip()
169 GlobalData.gGlobalDefines["EDK_SOURCE"] = GlobalData.gEdkSource
170 continue
171 elif List[0].strip() in ["WORKSPACE", "TARGET", "TOOLCHAIN"]:
172 GlobalData.gGlobalDefines[List[0].strip()] = List[1].strip()
173 else:
174 GlobalData.gCommandLineDefines[List[0].strip()] = List[1].strip()
175 else:
176 GlobalData.gCommandLineDefines[List[0].strip()] = "TRUE"
177 os.environ["WORKSPACE"] = Workspace
178
179 """call Workspace build create database"""
180 BuildWorkSpace = WorkspaceDatabase(None)
181 BuildWorkSpace.InitDatabase()
182
183 #
184 # Get files real name in workspace dir
185 #
186 GlobalData.gAllFiles = DirCache(Workspace)
187 GlobalData.gWorkspace = Workspace
188
189 if (Options.archList) :
190 ArchList = Options.archList.split(',')
191 else:
192 # EdkLogger.error("GenFds", OPTION_MISSING, "Missing build ARCH")
193 ArchList = BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, 'COMMON', Options.BuildTarget, Options.ToolChain].SupArchList
194
195 TargetArchList = set(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, 'COMMON', Options.BuildTarget, Options.ToolChain].SupArchList) & set(ArchList)
196 if len(TargetArchList) == 0:
197 EdkLogger.error("GenFds", GENFDS_ERROR, "Target ARCH %s not in platform supported ARCH %s" % (str(ArchList), str(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, 'COMMON'].SupArchList)))
198
199 for Arch in ArchList:
200 GenFdsGlobalVariable.OutputDirFromDscDict[Arch] = NormPath(BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, Options.BuildTarget, Options.ToolChain].OutputDirectory)
201 GenFdsGlobalVariable.PlatformName = BuildWorkSpace.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, Options.BuildTarget, Options.ToolChain].PlatformName
202
203 if (Options.outputDir):
204 OutputDirFromCommandLine = GenFdsGlobalVariable.ReplaceWorkspaceMacro(Options.outputDir)
205 if not os.path.isabs (OutputDirFromCommandLine):
206 OutputDirFromCommandLine = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, OutputDirFromCommandLine)
207 for Arch in ArchList:
208 GenFdsGlobalVariable.OutputDirDict[Arch] = OutputDirFromCommandLine
209 else:
210 for Arch in ArchList:
211 GenFdsGlobalVariable.OutputDirDict[Arch] = os.path.join(GenFdsGlobalVariable.OutputDirFromDscDict[Arch], GenFdsGlobalVariable.TargetName + '_' + GenFdsGlobalVariable.ToolChainTag)
212
213 for Key in GenFdsGlobalVariable.OutputDirDict:
214 OutputDir = GenFdsGlobalVariable.OutputDirDict[Key]
215 if OutputDir[0:2] == '..':
216 OutputDir = os.path.realpath(OutputDir)
217
218 if OutputDir[1] != ':':
219 OutputDir = os.path.join (GenFdsGlobalVariable.WorkSpaceDir, OutputDir)
220
221 if not os.path.exists(OutputDir):
222 EdkLogger.error("GenFds", FILE_NOT_FOUND, ExtraData=OutputDir)
223 GenFdsGlobalVariable.OutputDirDict[Key] = OutputDir
224
225 """ Parse Fdf file, has to place after build Workspace as FDF may contain macros from DSC file """
226 FdfParserObj = FdfParser.FdfParser(FdfFilename)
227 FdfParserObj.ParseFile()
228
229 if FdfParserObj.CycleReferenceCheck():
230 EdkLogger.error("GenFds", FORMAT_NOT_SUPPORTED, "Cycle Reference Detected in FDF file")
231
232 if (Options.uiFdName) :
233 if Options.uiFdName.upper() in FdfParserObj.Profile.FdDict.keys():
234 GenFds.OnlyGenerateThisFd = Options.uiFdName
235 else:
236 EdkLogger.error("GenFds", OPTION_VALUE_INVALID,
237 "No such an FD in FDF file: %s" % Options.uiFdName)
238
239 if (Options.uiFvName) :
240 if Options.uiFvName.upper() in FdfParserObj.Profile.FvDict.keys():
241 GenFds.OnlyGenerateThisFv = Options.uiFvName
242 else:
243 EdkLogger.error("GenFds", OPTION_VALUE_INVALID,
244 "No such an FV in FDF file: %s" % Options.uiFvName)
245
246 if (Options.uiCapName) :
247 if Options.uiCapName.upper() in FdfParserObj.Profile.CapsuleDict.keys():
248 GenFds.OnlyGenerateThisCap = Options.uiCapName
249 else:
250 EdkLogger.error("GenFds", OPTION_VALUE_INVALID,
251 "No such a Capsule in FDF file: %s" % Options.uiCapName)
252
253 """Modify images from build output if the feature of loading driver at fixed address is on."""
254 if GenFdsGlobalVariable.FixedLoadAddress:
255 GenFds.PreprocessImage(BuildWorkSpace, GenFdsGlobalVariable.ActivePlatform)
256 """Call GenFds"""
257 GenFds.GenFd('', FdfParserObj, BuildWorkSpace, ArchList)
258
259 """Generate GUID cross reference file"""
260 GenFds.GenerateGuidXRefFile(BuildWorkSpace, ArchList)
261
262 """Display FV space info."""
263 GenFds.DisplayFvSpaceInfo(FdfParserObj)
264
265 except FdfParser.Warning, X:
266 EdkLogger.error(X.ToolName, FORMAT_INVALID, File=X.FileName, Line=X.LineNumber, ExtraData=X.Message, RaiseError = False)
267 ReturnCode = FORMAT_INVALID
268 except FatalError, X:
269 if Options.debug != None:
270 import traceback
271 EdkLogger.quiet(traceback.format_exc())
272 ReturnCode = X.args[0]
273 except:
274 import traceback
275 EdkLogger.error(
276 "\nPython",
277 CODE_ERROR,
278 "Tools code failure",
279 ExtraData="Please send email to edk2-buildtools-devel@lists.sourceforge.net for help, attaching following call stack trace!\n",
280 RaiseError=False
281 )
282 EdkLogger.quiet(traceback.format_exc())
283 ReturnCode = CODE_ERROR
284 return ReturnCode
285
286 gParamCheck = []
287 def 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 #
301 def 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, AARCH64 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.")
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")
318 Parser.add_option("-b", "--buildtarget", type="string", dest="BuildTarget", help="Set the build TARGET, overrides target.txt TARGET setting.",
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 #
334 class GenFds :
335 FdfParsef = None
336 # FvName, FdName, CapName in FDF, Image file name
337 ImageBinDict = {}
338 OnlyGenerateThisFd = None
339 OnlyGenerateThisFv = None
340 OnlyGenerateThisCap = None
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
352 GenFdsGlobalVariable.VerboseLogger(" Generate all Fd images and their required FV and Capsule images!")
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
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:
362 FdObj.GenFd()
363 return
364 elif GenFds.OnlyGenerateThisFd == None and GenFds.OnlyGenerateThisFv == None:
365 for FdName in GenFdsGlobalVariable.FdfParser.Profile.FdDict.keys():
366 FdObj = GenFdsGlobalVariable.FdfParser.Profile.FdDict[FdName]
367 FdObj.GenFd()
368
369 GenFdsGlobalVariable.VerboseLogger("\n Generate other FV images! ")
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()
374 FvObj.AddToBuffer(Buffer)
375 Buffer.close()
376 return
377 elif GenFds.OnlyGenerateThisFv == None:
378 for FvName in GenFdsGlobalVariable.FdfParser.Profile.FvDict.keys():
379 Buffer = StringIO.StringIO('')
380 FvObj = GenFdsGlobalVariable.FdfParser.Profile.FvDict[FvName]
381 FvObj.AddToBuffer(Buffer)
382 Buffer.close()
383
384 if GenFds.OnlyGenerateThisFv == None and GenFds.OnlyGenerateThisFd == None and GenFds.OnlyGenerateThisCap == None:
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
391 if GenFdsGlobalVariable.FdfParser.Profile.OptRomDict != {}:
392 GenFdsGlobalVariable.VerboseLogger("\n Generate all Option ROM!")
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):
403 DefaultBlockSize = 0x1
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)
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')
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):
488 PcdDict = BuildDb.BuildObject[DscFile, 'COMMON', GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].Pcds
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
507 ModuleDict = BuildDb.BuildObject[DscFile, 'COMMON', GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag].Modules
508 for Key in ModuleDict:
509 ModuleObj = BuildDb.BuildObject[Key, 'COMMON', GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag]
510 print ModuleObj.BaseName + ' ' + ModuleObj.ModuleType
511
512 def GenerateGuidXRefFile(BuildDb, ArchList):
513 GuidXRefFileName = os.path.join(GenFdsGlobalVariable.FvDir, "Guid.xref")
514 GuidXRefFile = StringIO.StringIO('')
515 GuidDict = {}
516 for Arch in ArchList:
517 PlatformDataBase = BuildDb.BuildObject[GenFdsGlobalVariable.ActivePlatform, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag]
518 for ModuleFile in PlatformDataBase.Modules:
519 Module = BuildDb.BuildObject[ModuleFile, Arch, GenFdsGlobalVariable.TargetName, GenFdsGlobalVariable.ToolChainTag]
520 GuidXRefFile.write("%s %s\n" % (Module.Guid, Module.BaseName))
521 for key, item in Module.Protocols.items():
522 GuidDict[key] = item
523 for key, item in Module.Guids.items():
524 GuidDict[key] = item
525 for key, item in Module.Ppis.items():
526 GuidDict[key] = item
527 # Append GUIDs, Protocols, and PPIs to the Xref file
528 GuidXRefFile.write("\n")
529 for key, item in GuidDict.items():
530 GuidXRefFile.write("%s %s\n" % (GuidStructureStringToGuidString(item).upper(), key))
531
532 if GuidXRefFile.getvalue():
533 SaveFileOnChange(GuidXRefFileName, GuidXRefFile.getvalue(), False)
534 GenFdsGlobalVariable.InfLogger("\nGUID cross reference file can be found at %s" % GuidXRefFileName)
535 elif os.path.exists(GuidXRefFileName):
536 os.remove(GuidXRefFileName)
537 GuidXRefFile.close()
538
539 ##Define GenFd as static function
540 GenFd = staticmethod(GenFd)
541 GetFvBlockSize = staticmethod(GetFvBlockSize)
542 DisplayFvSpaceInfo = staticmethod(DisplayFvSpaceInfo)
543 PreprocessImage = staticmethod(PreprocessImage)
544 GenerateGuidXRefFile = staticmethod(GenerateGuidXRefFile)
545
546 if __name__ == '__main__':
547 r = main()
548 ## 0-127 is a safe return range, and 1 is a standard default error
549 if r < 0 or r > 127: r = 1
550 sys.exit(r)
551