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