2 # Generate AutoGen.h, AutoGen.c and *.depex files
4 # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>
5 # This program and the accompanying materials
6 # are licensed and made available under the terms and conditions of the BSD License
7 # which accompanies this distribution. The full text of the license may be found at
8 # http://opensource.org/licenses/bsd-license.php
10 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
16 import Common
.LongFilePathOs
as os
18 import os
.path
as path
25 from StringIO
import StringIO
27 from StrGather
import *
28 from BuildEngine
import BuildRule
30 from Common
.LongFilePathSupport
import CopyLongFilePath
31 from Common
.BuildToolError
import *
32 from Common
.DataType
import *
33 from Common
.Misc
import *
34 from Common
.String
import *
35 import Common
.GlobalData
as GlobalData
36 from GenFds
.FdfParser
import *
37 from CommonDataClass
.CommonClass
import SkuInfoClass
38 from Workspace
.BuildClassObject
import *
39 from GenPatchPcdTable
.GenPatchPcdTable
import parsePcdInfoFromMapFile
40 import Common
.VpdInfoFile
as VpdInfoFile
41 from GenPcdDb
import CreatePcdDatabaseCode
42 from Workspace
.MetaFileCommentParser
import UsageList
43 from Common
.MultipleWorkspace
import MultipleWorkspace
as mws
44 import InfSectionParser
47 from GenVar
import VariableMgr
,var_info
48 from collections
import OrderedDict
49 from collections
import defaultdict
51 ## Regular expression for splitting Dependency Expression string into tokens
52 gDepexTokenPattern
= re
.compile("(\(|\)|\w+| \S+\.inf)")
54 ## Regular expression for match: PCD(xxxx.yyy)
55 gPCDAsGuidPattern
= re
.compile(r
"^PCD\(.+\..+\)$")
58 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT
59 # is the former use /I , the Latter used -I to specify include directories
61 gBuildOptIncludePatternMsft
= re
.compile(r
"(?:.*?)/I[ \t]*([^ ]*)", re
.MULTILINE | re
.DOTALL
)
62 gBuildOptIncludePatternOther
= re
.compile(r
"(?:.*?)-I[ \t]*([^ ]*)", re
.MULTILINE | re
.DOTALL
)
65 # Match name = variable
67 gEfiVarStoreNamePattern
= re
.compile("\s*name\s*=\s*(\w+)")
69 # The format of guid in efivarstore statement likes following and must be correct:
70 # guid = {0xA04A27f4, 0xDF00, 0x4D42, {0xB5, 0x52, 0x39, 0x51, 0x13, 0x02, 0x11, 0x3D}}
72 gEfiVarStoreGuidPattern
= re
.compile("\s*guid\s*=\s*({.*?{.*?}\s*})")
74 ## Mapping Makefile type
75 gMakeTypeMap
= {"MSFT":"nmake", "GCC":"gmake"}
78 ## Build rule configuration file
79 gDefaultBuildRuleFile
= 'build_rule.txt'
81 ## Tools definition configuration file
82 gDefaultToolsDefFile
= 'tools_def.txt'
84 ## Build rule default version
85 AutoGenReqBuildRuleVerNum
= "0.1"
87 ## default file name for AutoGen
88 gAutoGenCodeFileName
= "AutoGen.c"
89 gAutoGenHeaderFileName
= "AutoGen.h"
90 gAutoGenStringFileName
= "%(module_name)sStrDefs.h"
91 gAutoGenStringFormFileName
= "%(module_name)sStrDefs.hpk"
92 gAutoGenDepexFileName
= "%(module_name)s.depex"
93 gAutoGenImageDefFileName
= "%(module_name)sImgDefs.h"
94 gAutoGenIdfFileName
= "%(module_name)sIdf.hpk"
95 gInfSpecVersion
= "0x00010017"
98 # Template string to generic AsBuilt INF
100 gAsBuiltInfHeaderString
= TemplateString("""${header_comments}
103 # FILE auto-generated
106 INF_VERSION = ${module_inf_version}
107 BASE_NAME = ${module_name}
108 FILE_GUID = ${module_guid}
109 MODULE_TYPE = ${module_module_type}${BEGIN}
110 VERSION_STRING = ${module_version_string}${END}${BEGIN}
111 PCD_IS_DRIVER = ${pcd_is_driver_string}${END}${BEGIN}
112 UEFI_SPECIFICATION_VERSION = ${module_uefi_specification_version}${END}${BEGIN}
113 PI_SPECIFICATION_VERSION = ${module_pi_specification_version}${END}${BEGIN}
114 ENTRY_POINT = ${module_entry_point}${END}${BEGIN}
115 UNLOAD_IMAGE = ${module_unload_image}${END}${BEGIN}
116 CONSTRUCTOR = ${module_constructor}${END}${BEGIN}
117 DESTRUCTOR = ${module_destructor}${END}${BEGIN}
118 SHADOW = ${module_shadow}${END}${BEGIN}
119 PCI_VENDOR_ID = ${module_pci_vendor_id}${END}${BEGIN}
120 PCI_DEVICE_ID = ${module_pci_device_id}${END}${BEGIN}
121 PCI_CLASS_CODE = ${module_pci_class_code}${END}${BEGIN}
122 PCI_REVISION = ${module_pci_revision}${END}${BEGIN}
123 BUILD_NUMBER = ${module_build_number}${END}${BEGIN}
124 SPEC = ${module_spec}${END}${BEGIN}
125 UEFI_HII_RESOURCE_SECTION = ${module_uefi_hii_resource_section}${END}${BEGIN}
126 MODULE_UNI_FILE = ${module_uni_file}${END}
128 [Packages.${module_arch}]${BEGIN}
129 ${package_item}${END}
131 [Binaries.${module_arch}]${BEGIN}
134 [PatchPcd.${module_arch}]${BEGIN}
138 [Protocols.${module_arch}]${BEGIN}
142 [Ppis.${module_arch}]${BEGIN}
146 [Guids.${module_arch}]${BEGIN}
150 [PcdEx.${module_arch}]${BEGIN}
154 [LibraryClasses.${module_arch}]
155 ## @LIB_INSTANCES${BEGIN}
156 # ${libraryclasses_item}${END}
160 ${userextension_tianocore_item}
164 [BuildOptions.${module_arch}]
166 ## ${flags_item}${END}
169 ## Base class for AutoGen
171 # This class just implements the cache mechanism of AutoGen objects.
173 class AutoGen(object):
174 # database to maintain the objects in each child class
175 __ObjectCache
= {} # (BuildTarget, ToolChain, ARCH, platform file): AutoGen object
179 # @param Class class object of real AutoGen class
180 # (WorkspaceAutoGen, ModuleAutoGen or PlatformAutoGen)
181 # @param Workspace Workspace directory or WorkspaceAutoGen object
182 # @param MetaFile The path of meta file
183 # @param Target Build target
184 # @param Toolchain Tool chain name
185 # @param Arch Target arch
186 # @param *args The specific class related parameters
187 # @param **kwargs The specific class related dict parameters
189 def __new__(cls
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
190 # check if the object has been created
191 Key
= (Target
, Toolchain
, Arch
, MetaFile
)
193 # if it exists, just return it directly
194 return cls
.__ObjectCache
[Key
]
196 # it didnt exist. create it, cache it, then return it
197 cls
.__ObjectCache
[Key
] = super(AutoGen
, cls
).__new
__(cls
)
198 return cls
.__ObjectCache
[Key
]
200 def __init__ (self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
201 super(AutoGen
, self
).__init
__(self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
)
205 # The file path of platform file will be used to represent hash value of this object
207 # @retval int Hash value of the file path of platform file
210 return hash(self
.MetaFile
)
214 # The file path of platform file will be used to represent this object
216 # @retval string String of platform file path
219 return str(self
.MetaFile
)
222 def __eq__(self
, Other
):
223 return Other
and self
.MetaFile
== Other
225 ## Workspace AutoGen class
227 # This class is used mainly to control the whole platform build for different
228 # architecture. This class will generate top level makefile.
230 class WorkspaceAutoGen(AutoGen
):
231 # call super().__init__ then call the worker function with different parameter count
232 def __init__(self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
236 super(WorkspaceAutoGen
, self
).__init
__(Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
)
237 self
._InitWorker
(Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
)
240 ## Initialize WorkspaceAutoGen
242 # @param WorkspaceDir Root directory of workspace
243 # @param ActivePlatform Meta-file of active platform
244 # @param Target Build target
245 # @param Toolchain Tool chain name
246 # @param ArchList List of architecture of current build
247 # @param MetaFileDb Database containing meta-files
248 # @param BuildConfig Configuration of build
249 # @param ToolDefinition Tool chain definitions
250 # @param FlashDefinitionFile File of flash definition
251 # @param Fds FD list to be generated
252 # @param Fvs FV list to be generated
253 # @param Caps Capsule list to be generated
254 # @param SkuId SKU id from command line
256 def _InitWorker(self
, WorkspaceDir
, ActivePlatform
, Target
, Toolchain
, ArchList
, MetaFileDb
,
257 BuildConfig
, ToolDefinition
, FlashDefinitionFile
='', Fds
=None, Fvs
=None, Caps
=None, SkuId
='', UniFlag
=None,
258 Progress
=None, BuildModule
=None):
259 self
.BuildDatabase
= MetaFileDb
260 self
.MetaFile
= ActivePlatform
261 self
.WorkspaceDir
= WorkspaceDir
262 self
.Platform
= self
.BuildDatabase
[self
.MetaFile
, TAB_ARCH_COMMON
, Target
, Toolchain
]
263 GlobalData
.gActivePlatform
= self
.Platform
264 self
.BuildTarget
= Target
265 self
.ToolChain
= Toolchain
266 self
.ArchList
= ArchList
268 self
.UniFlag
= UniFlag
270 self
.TargetTxt
= BuildConfig
271 self
.ToolDef
= ToolDefinition
272 self
.FdfFile
= FlashDefinitionFile
273 self
.FdTargetList
= Fds
if Fds
else []
274 self
.FvTargetList
= Fvs
if Fvs
else []
275 self
.CapTargetList
= Caps
if Caps
else []
276 self
.AutoGenObjectList
= []
277 self
._BuildDir
= None
279 self
._MakeFileDir
= None
280 self
._BuildCommand
= None
283 # there's many relative directory operations, so ...
284 os
.chdir(self
.WorkspaceDir
)
289 if not self
.ArchList
:
290 ArchList
= set(self
.Platform
.SupArchList
)
292 ArchList
= set(self
.ArchList
) & set(self
.Platform
.SupArchList
)
294 EdkLogger
.error("build", PARAMETER_INVALID
,
295 ExtraData
= "Invalid ARCH specified. [Valid ARCH: %s]" % (" ".join(self
.Platform
.SupArchList
)))
296 elif self
.ArchList
and len(ArchList
) != len(self
.ArchList
):
297 SkippedArchList
= set(self
.ArchList
).symmetric_difference(set(self
.Platform
.SupArchList
))
298 EdkLogger
.verbose("\nArch [%s] is ignored because the platform supports [%s] only!"
299 % (" ".join(SkippedArchList
), " ".join(self
.Platform
.SupArchList
)))
300 self
.ArchList
= tuple(ArchList
)
302 # Validate build target
303 if self
.BuildTarget
not in self
.Platform
.BuildTargets
:
304 EdkLogger
.error("build", PARAMETER_INVALID
,
305 ExtraData
="Build target [%s] is not supported by the platform. [Valid target: %s]"
306 % (self
.BuildTarget
, " ".join(self
.Platform
.BuildTargets
)))
309 # parse FDF file to get PCDs in it, if any
311 self
.FdfFile
= self
.Platform
.FlashDefinition
315 EdkLogger
.info('%-16s = %s' % ("Architecture(s)", ' '.join(self
.ArchList
)))
316 EdkLogger
.info('%-16s = %s' % ("Build target", self
.BuildTarget
))
317 EdkLogger
.info('%-16s = %s' % ("Toolchain", self
.ToolChain
))
319 EdkLogger
.info('\n%-24s = %s' % ("Active Platform", self
.Platform
))
321 EdkLogger
.info('%-24s = %s' % ("Active Module", BuildModule
))
324 EdkLogger
.info('%-24s = %s' % ("Flash Image Definition", self
.FdfFile
))
326 EdkLogger
.verbose("\nFLASH_DEFINITION = %s" % self
.FdfFile
)
329 Progress
.Start("\nProcessing meta-data")
333 # Mark now build in AutoGen Phase
335 GlobalData
.gAutoGenPhase
= True
336 Fdf
= FdfParser(self
.FdfFile
.Path
)
338 GlobalData
.gFdfParser
= Fdf
339 GlobalData
.gAutoGenPhase
= False
340 PcdSet
= Fdf
.Profile
.PcdDict
341 if Fdf
.CurrentFdName
and Fdf
.CurrentFdName
in Fdf
.Profile
.FdDict
:
342 FdDict
= Fdf
.Profile
.FdDict
[Fdf
.CurrentFdName
]
343 for FdRegion
in FdDict
.RegionList
:
344 if str(FdRegion
.RegionType
) is 'FILE' and self
.Platform
.VpdToolGuid
in str(FdRegion
.RegionDataList
):
345 if int(FdRegion
.Offset
) % 8 != 0:
346 EdkLogger
.error("build", FORMAT_INVALID
, 'The VPD Base Address %s must be 8-byte aligned.' % (FdRegion
.Offset
))
347 ModuleList
= Fdf
.Profile
.InfList
348 self
.FdfProfile
= Fdf
.Profile
349 for fvname
in self
.FvTargetList
:
350 if fvname
.upper() not in self
.FdfProfile
.FvDict
:
351 EdkLogger
.error("build", OPTION_VALUE_INVALID
,
352 "No such an FV in FDF file: %s" % fvname
)
354 # In DSC file may use FILE_GUID to override the module, then in the Platform.Modules use FILE_GUIDmodule.inf as key,
355 # but the path (self.MetaFile.Path) is the real path
356 for key
in self
.FdfProfile
.InfDict
:
358 MetaFile_cache
= defaultdict(set)
359 for Arch
in self
.ArchList
:
360 Current_Platform_cache
= self
.BuildDatabase
[self
.MetaFile
, Arch
, Target
, Toolchain
]
361 for Pkey
in Current_Platform_cache
.Modules
:
362 MetaFile_cache
[Arch
].add(Current_Platform_cache
.Modules
[Pkey
].MetaFile
)
363 for Inf
in self
.FdfProfile
.InfDict
[key
]:
364 ModuleFile
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, Arch
)
365 for Arch
in self
.ArchList
:
366 if ModuleFile
in MetaFile_cache
[Arch
]:
369 ModuleData
= self
.BuildDatabase
[ModuleFile
, Arch
, Target
, Toolchain
]
370 if not ModuleData
.IsBinaryModule
:
371 EdkLogger
.error('build', PARSER_ERROR
, "Module %s NOT found in DSC file; Is it really a binary module?" % ModuleFile
)
374 for Arch
in self
.ArchList
:
376 Platform
= self
.BuildDatabase
[self
.MetaFile
, Arch
, Target
, Toolchain
]
378 for Pkey
in Platform
.Modules
:
379 MetaFileList
.add(Platform
.Modules
[Pkey
].MetaFile
)
380 for Inf
in self
.FdfProfile
.InfDict
[key
]:
381 ModuleFile
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, Arch
)
382 if ModuleFile
in MetaFileList
:
384 ModuleData
= self
.BuildDatabase
[ModuleFile
, Arch
, Target
, Toolchain
]
385 if not ModuleData
.IsBinaryModule
:
386 EdkLogger
.error('build', PARSER_ERROR
, "Module %s NOT found in DSC file; Is it really a binary module?" % ModuleFile
)
391 self
.FdfProfile
= None
392 if self
.FdTargetList
:
393 EdkLogger
.info("No flash definition file found. FD [%s] will be ignored." % " ".join(self
.FdTargetList
))
394 self
.FdTargetList
= []
395 if self
.FvTargetList
:
396 EdkLogger
.info("No flash definition file found. FV [%s] will be ignored." % " ".join(self
.FvTargetList
))
397 self
.FvTargetList
= []
398 if self
.CapTargetList
:
399 EdkLogger
.info("No flash definition file found. Capsule [%s] will be ignored." % " ".join(self
.CapTargetList
))
400 self
.CapTargetList
= []
402 # apply SKU and inject PCDs from Flash Definition file
403 for Arch
in self
.ArchList
:
404 Platform
= self
.BuildDatabase
[self
.MetaFile
, Arch
, Target
, Toolchain
]
405 PlatformPcds
= Platform
.Pcds
406 self
._GuidDict
= Platform
._GuidDict
407 SourcePcdDict
= {TAB_PCDS_DYNAMIC_EX
:set(), TAB_PCDS_PATCHABLE_IN_MODULE
:set(),TAB_PCDS_DYNAMIC
:set(),TAB_PCDS_FIXED_AT_BUILD
:set()}
408 BinaryPcdDict
= {TAB_PCDS_DYNAMIC_EX
:set(), TAB_PCDS_PATCHABLE_IN_MODULE
:set()}
409 SourcePcdDict_Keys
= SourcePcdDict
.keys()
410 BinaryPcdDict_Keys
= BinaryPcdDict
.keys()
412 # generate the SourcePcdDict and BinaryPcdDict
413 PGen
= PlatformAutoGen(self
, self
.MetaFile
, Target
, Toolchain
, Arch
)
414 for BuildData
in PGen
.BuildDatabase
._CACHE
_.values():
415 if BuildData
.Arch
!= Arch
:
417 if BuildData
.MetaFile
.Ext
== '.inf':
418 for key
in BuildData
.Pcds
:
419 if BuildData
.Pcds
[key
].Pending
:
420 if key
in Platform
.Pcds
:
421 PcdInPlatform
= Platform
.Pcds
[key
]
422 if PcdInPlatform
.Type
:
423 BuildData
.Pcds
[key
].Type
= PcdInPlatform
.Type
425 if BuildData
.MetaFile
in Platform
.Modules
:
426 PlatformModule
= Platform
.Modules
[str(BuildData
.MetaFile
)]
427 if key
in PlatformModule
.Pcds
:
428 PcdInPlatform
= PlatformModule
.Pcds
[key
]
429 if PcdInPlatform
.Type
:
430 BuildData
.Pcds
[key
].Type
= PcdInPlatform
.Type
432 if TAB_PCDS_DYNAMIC_EX
in BuildData
.Pcds
[key
].Type
:
433 if BuildData
.IsBinaryModule
:
434 BinaryPcdDict
[TAB_PCDS_DYNAMIC_EX
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
436 SourcePcdDict
[TAB_PCDS_DYNAMIC_EX
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
438 elif TAB_PCDS_PATCHABLE_IN_MODULE
in BuildData
.Pcds
[key
].Type
:
439 if BuildData
.MetaFile
.Ext
== '.inf':
440 if BuildData
.IsBinaryModule
:
441 BinaryPcdDict
[TAB_PCDS_PATCHABLE_IN_MODULE
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
443 SourcePcdDict
[TAB_PCDS_PATCHABLE_IN_MODULE
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
445 elif TAB_PCDS_DYNAMIC
in BuildData
.Pcds
[key
].Type
:
446 SourcePcdDict
[TAB_PCDS_DYNAMIC
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
447 elif TAB_PCDS_FIXED_AT_BUILD
in BuildData
.Pcds
[key
].Type
:
448 SourcePcdDict
[TAB_PCDS_FIXED_AT_BUILD
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
452 # A PCD can only use one type for all source modules
454 for i
in SourcePcdDict_Keys
:
455 for j
in SourcePcdDict_Keys
:
457 Intersections
= SourcePcdDict
[i
].intersection(SourcePcdDict
[j
])
458 if len(Intersections
) > 0:
462 "Building modules from source INFs, following PCD use %s and %s access method. It must be corrected to use only one access method." % (i
, j
),
463 ExtraData
="%s" % '\n\t'.join([str(P
[1]+'.'+P
[0]) for P
in Intersections
])
467 # intersection the BinaryPCD for Mixed PCD
469 for i
in BinaryPcdDict_Keys
:
470 for j
in BinaryPcdDict_Keys
:
472 Intersections
= BinaryPcdDict
[i
].intersection(BinaryPcdDict
[j
])
473 for item
in Intersections
:
474 NewPcd1
= (item
[0] + '_' + i
, item
[1])
475 NewPcd2
= (item
[0] + '_' + j
, item
[1])
476 if item
not in GlobalData
.MixedPcd
:
477 GlobalData
.MixedPcd
[item
] = [NewPcd1
, NewPcd2
]
479 if NewPcd1
not in GlobalData
.MixedPcd
[item
]:
480 GlobalData
.MixedPcd
[item
].append(NewPcd1
)
481 if NewPcd2
not in GlobalData
.MixedPcd
[item
]:
482 GlobalData
.MixedPcd
[item
].append(NewPcd2
)
485 # intersection the SourcePCD and BinaryPCD for Mixed PCD
487 for i
in SourcePcdDict_Keys
:
488 for j
in BinaryPcdDict_Keys
:
490 Intersections
= SourcePcdDict
[i
].intersection(BinaryPcdDict
[j
])
491 for item
in Intersections
:
492 NewPcd1
= (item
[0] + '_' + i
, item
[1])
493 NewPcd2
= (item
[0] + '_' + j
, item
[1])
494 if item
not in GlobalData
.MixedPcd
:
495 GlobalData
.MixedPcd
[item
] = [NewPcd1
, NewPcd2
]
497 if NewPcd1
not in GlobalData
.MixedPcd
[item
]:
498 GlobalData
.MixedPcd
[item
].append(NewPcd1
)
499 if NewPcd2
not in GlobalData
.MixedPcd
[item
]:
500 GlobalData
.MixedPcd
[item
].append(NewPcd2
)
502 for BuildData
in PGen
.BuildDatabase
._CACHE
_.values():
503 if BuildData
.Arch
!= Arch
:
505 for key
in BuildData
.Pcds
:
506 for SinglePcd
in GlobalData
.MixedPcd
:
507 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) == SinglePcd
:
508 for item
in GlobalData
.MixedPcd
[SinglePcd
]:
509 Pcd_Type
= item
[0].split('_')[-1]
510 if (Pcd_Type
== BuildData
.Pcds
[key
].Type
) or (Pcd_Type
== TAB_PCDS_DYNAMIC_EX
and BuildData
.Pcds
[key
].Type
in PCD_DYNAMIC_EX_TYPE_SET
) or \
511 (Pcd_Type
== TAB_PCDS_DYNAMIC
and BuildData
.Pcds
[key
].Type
in PCD_DYNAMIC_TYPE_SET
):
512 Value
= BuildData
.Pcds
[key
]
513 Value
.TokenCName
= BuildData
.Pcds
[key
].TokenCName
+ '_' + Pcd_Type
515 newkey
= (Value
.TokenCName
, key
[1])
517 newkey
= (Value
.TokenCName
, key
[1], key
[2])
518 del BuildData
.Pcds
[key
]
519 BuildData
.Pcds
[newkey
] = Value
523 # handle the mixed pcd in FDF file
525 if key
in GlobalData
.MixedPcd
:
528 for item
in GlobalData
.MixedPcd
[key
]:
531 #Collect package set information from INF of FDF
533 for Inf
in ModuleList
:
534 ModuleFile
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, Arch
)
535 if ModuleFile
in Platform
.Modules
:
537 ModuleData
= self
.BuildDatabase
[ModuleFile
, Arch
, Target
, Toolchain
]
538 PkgSet
.update(ModuleData
.Packages
)
539 Pkgs
= list(PkgSet
) + list(PGen
.PackageList
)
544 DecPcds
.add((Pcd
[0], Pcd
[1]))
545 DecPcdsKey
.add((Pcd
[0], Pcd
[1], Pcd
[2]))
547 Platform
.SkuName
= self
.SkuId
548 for Name
, Guid
in PcdSet
:
549 if (Name
, Guid
) not in DecPcds
:
553 "PCD (%s.%s) used in FDF is not declared in DEC files." % (Guid
, Name
),
554 File
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
][0],
555 Line
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
][1]
558 # Check whether Dynamic or DynamicEx PCD used in FDF file. If used, build break and give a error message.
559 if (Name
, Guid
, TAB_PCDS_FIXED_AT_BUILD
) in DecPcdsKey \
560 or (Name
, Guid
, TAB_PCDS_PATCHABLE_IN_MODULE
) in DecPcdsKey \
561 or (Name
, Guid
, TAB_PCDS_FEATURE_FLAG
) in DecPcdsKey
:
562 Platform
.AddPcd(Name
, Guid
, PcdSet
[Name
, Guid
])
564 elif (Name
, Guid
, TAB_PCDS_DYNAMIC
) in DecPcdsKey
or (Name
, Guid
, TAB_PCDS_DYNAMIC_EX
) in DecPcdsKey
:
568 "Using Dynamic or DynamicEx type of PCD [%s.%s] in FDF file is not allowed." % (Guid
, Name
),
569 File
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
][0],
570 Line
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
][1]
573 Pa
= PlatformAutoGen(self
, self
.MetaFile
, Target
, Toolchain
, Arch
)
575 # Explicitly collect platform's dynamic PCDs
577 Pa
.CollectPlatformDynamicPcds()
578 Pa
.CollectFixedAtBuildPcds()
579 self
.AutoGenObjectList
.append(Pa
)
582 # Generate Package level hash value
584 GlobalData
.gPackageHash
[Arch
] = {}
585 if GlobalData
.gUseHashCache
:
587 self
._GenPkgLevelHash
(Pkg
)
590 # Check PCDs token value conflict in each DEC file.
592 self
._CheckAllPcdsTokenValueConflict
()
595 # Check PCD type and definition between DSC and DEC
597 self
._CheckPcdDefineAndType
()
600 # self._CheckDuplicateInFV(Fdf)
603 # Create BuildOptions Macro & PCD metafile, also add the Active Platform and FDF file.
605 content
= 'gCommandLineDefines: '
606 content
+= str(GlobalData
.gCommandLineDefines
)
607 content
+= os
.linesep
608 content
+= 'BuildOptionPcd: '
609 content
+= str(GlobalData
.BuildOptionPcd
)
610 content
+= os
.linesep
611 content
+= 'Active Platform: '
612 content
+= str(self
.Platform
)
613 content
+= os
.linesep
615 content
+= 'Flash Image Definition: '
616 content
+= str(self
.FdfFile
)
617 content
+= os
.linesep
618 SaveFileOnChange(os
.path
.join(self
.BuildDir
, 'BuildOptions'), content
, False)
621 # Create PcdToken Number file for Dynamic/DynamicEx Pcd.
623 PcdTokenNumber
= 'PcdTokenNumber: '
624 if Pa
.PcdTokenNumber
:
625 if Pa
.DynamicPcdList
:
626 for Pcd
in Pa
.DynamicPcdList
:
627 PcdTokenNumber
+= os
.linesep
628 PcdTokenNumber
+= str((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
))
629 PcdTokenNumber
+= ' : '
630 PcdTokenNumber
+= str(Pa
.PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
])
631 SaveFileOnChange(os
.path
.join(self
.BuildDir
, 'PcdTokenNumber'), PcdTokenNumber
, False)
634 # Get set of workspace metafiles
636 AllWorkSpaceMetaFiles
= self
._GetMetaFiles
(Target
, Toolchain
, Arch
)
639 # Retrieve latest modified time of all metafiles
642 for f
in AllWorkSpaceMetaFiles
:
643 if os
.stat(f
)[8] > SrcTimeStamp
:
644 SrcTimeStamp
= os
.stat(f
)[8]
645 self
._SrcTimeStamp
= SrcTimeStamp
647 if GlobalData
.gUseHashCache
:
649 for files
in AllWorkSpaceMetaFiles
:
650 if files
.endswith('.dec'):
656 SaveFileOnChange(os
.path
.join(self
.BuildDir
, 'AutoGen.hash'), m
.hexdigest(), True)
657 GlobalData
.gPlatformHash
= m
.hexdigest()
660 # Write metafile list to build directory
662 AutoGenFilePath
= os
.path
.join(self
.BuildDir
, 'AutoGen')
663 if os
.path
.exists (AutoGenFilePath
):
664 os
.remove(AutoGenFilePath
)
665 if not os
.path
.exists(self
.BuildDir
):
666 os
.makedirs(self
.BuildDir
)
667 with
open(os
.path
.join(self
.BuildDir
, 'AutoGen'), 'w+') as file:
668 for f
in AllWorkSpaceMetaFiles
:
672 def _GenPkgLevelHash(self
, Pkg
):
673 PkgDir
= os
.path
.join(self
.BuildDir
, Pkg
.Arch
, Pkg
.PackageName
)
674 CreateDirectory(PkgDir
)
675 HashFile
= os
.path
.join(PkgDir
, Pkg
.PackageName
+ '.hash')
677 # Get .dec file's hash value
678 f
= open(Pkg
.MetaFile
.Path
, 'r')
682 # Get include files hash value
684 for inc
in Pkg
.Includes
:
685 for Root
, Dirs
, Files
in os
.walk(str(inc
)):
687 File_Path
= os
.path
.join(Root
, File
)
688 f
= open(File_Path
, 'r')
692 SaveFileOnChange(HashFile
, m
.hexdigest(), True)
693 if Pkg
.PackageName
not in GlobalData
.gPackageHash
[Pkg
.Arch
]:
694 GlobalData
.gPackageHash
[Pkg
.Arch
][Pkg
.PackageName
] = m
.hexdigest()
696 def _GetMetaFiles(self
, Target
, Toolchain
, Arch
):
697 AllWorkSpaceMetaFiles
= set()
702 AllWorkSpaceMetaFiles
.add (self
.FdfFile
.Path
)
704 FdfFiles
= GlobalData
.gFdfParser
.GetAllIncludedFile()
706 AllWorkSpaceMetaFiles
.add (f
.FileName
)
710 AllWorkSpaceMetaFiles
.add(self
.MetaFile
.Path
)
713 # add build_rule.txt & tools_def.txt
715 AllWorkSpaceMetaFiles
.add(os
.path
.join(GlobalData
.gConfDirectory
, gDefaultBuildRuleFile
))
716 AllWorkSpaceMetaFiles
.add(os
.path
.join(GlobalData
.gConfDirectory
, gDefaultToolsDefFile
))
718 # add BuildOption metafile
720 AllWorkSpaceMetaFiles
.add(os
.path
.join(self
.BuildDir
, 'BuildOptions'))
722 # add PcdToken Number file for Dynamic/DynamicEx Pcd
724 AllWorkSpaceMetaFiles
.add(os
.path
.join(self
.BuildDir
, 'PcdTokenNumber'))
726 for Arch
in self
.ArchList
:
727 Platform
= self
.BuildDatabase
[self
.MetaFile
, Arch
, Target
, Toolchain
]
728 PGen
= PlatformAutoGen(self
, self
.MetaFile
, Target
, Toolchain
, Arch
)
733 for Package
in PGen
.PackageList
:
734 AllWorkSpaceMetaFiles
.add(Package
.MetaFile
.Path
)
739 for filePath
in Platform
._RawData
.IncludedFiles
:
740 AllWorkSpaceMetaFiles
.add(filePath
.Path
)
742 return AllWorkSpaceMetaFiles
744 ## _CheckDuplicateInFV() method
746 # Check whether there is duplicate modules/files exist in FV section.
747 # The check base on the file GUID;
749 def _CheckDuplicateInFV(self
, Fdf
):
750 for Fv
in Fdf
.Profile
.FvDict
:
752 for FfsFile
in Fdf
.Profile
.FvDict
[Fv
].FfsList
:
753 if FfsFile
.InfFileName
and FfsFile
.NameGuid
is None:
758 for Pa
in self
.AutoGenObjectList
:
761 for Module
in Pa
.ModuleAutoGenList
:
762 if path
.normpath(Module
.MetaFile
.File
) == path
.normpath(FfsFile
.InfFileName
):
764 if Module
.Guid
.upper() not in _GuidDict
:
765 _GuidDict
[Module
.Guid
.upper()] = FfsFile
768 EdkLogger
.error("build",
770 "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile
.CurrentLineNum
,
771 FfsFile
.CurrentLineContent
,
772 _GuidDict
[Module
.Guid
.upper()].CurrentLineNum
,
773 _GuidDict
[Module
.Guid
.upper()].CurrentLineContent
,
774 Module
.Guid
.upper()),
775 ExtraData
=self
.FdfFile
)
777 # Some INF files not have entity in DSC file.
780 if FfsFile
.InfFileName
.find('$') == -1:
781 InfPath
= NormPath(FfsFile
.InfFileName
)
782 if not os
.path
.exists(InfPath
):
783 EdkLogger
.error('build', GENFDS_ERROR
, "Non-existant Module %s !" % (FfsFile
.InfFileName
))
785 PathClassObj
= PathClass(FfsFile
.InfFileName
, self
.WorkspaceDir
)
787 # Here we just need to get FILE_GUID from INF file, use 'COMMON' as ARCH attribute. and use
788 # BuildObject from one of AutoGenObjectList is enough.
790 InfObj
= self
.AutoGenObjectList
[0].BuildDatabase
.WorkspaceDb
.BuildObject
[PathClassObj
, TAB_ARCH_COMMON
, self
.BuildTarget
, self
.ToolChain
]
791 if InfObj
.Guid
.upper() not in _GuidDict
:
792 _GuidDict
[InfObj
.Guid
.upper()] = FfsFile
794 EdkLogger
.error("build",
796 "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile
.CurrentLineNum
,
797 FfsFile
.CurrentLineContent
,
798 _GuidDict
[InfObj
.Guid
.upper()].CurrentLineNum
,
799 _GuidDict
[InfObj
.Guid
.upper()].CurrentLineContent
,
800 InfObj
.Guid
.upper()),
801 ExtraData
=self
.FdfFile
)
804 if FfsFile
.NameGuid
is not None:
806 # If the NameGuid reference a PCD name.
807 # The style must match: PCD(xxxx.yyy)
809 if gPCDAsGuidPattern
.match(FfsFile
.NameGuid
):
811 # Replace the PCD value.
813 _PcdName
= FfsFile
.NameGuid
.lstrip("PCD(").rstrip(")")
815 for Pa
in self
.AutoGenObjectList
:
817 for PcdItem
in Pa
.AllPcdList
:
818 if (PcdItem
.TokenSpaceGuidCName
+ "." + PcdItem
.TokenCName
) == _PcdName
:
820 # First convert from CFormatGuid to GUID string
822 _PcdGuidString
= GuidStructureStringToGuidString(PcdItem
.DefaultValue
)
824 if not _PcdGuidString
:
826 # Then try Byte array.
828 _PcdGuidString
= GuidStructureByteArrayToGuidString(PcdItem
.DefaultValue
)
830 if not _PcdGuidString
:
832 # Not Byte array or CFormat GUID, raise error.
834 EdkLogger
.error("build",
836 "The format of PCD value is incorrect. PCD: %s , Value: %s\n" % (_PcdName
, PcdItem
.DefaultValue
),
837 ExtraData
=self
.FdfFile
)
839 if _PcdGuidString
.upper() not in _GuidDict
:
840 _GuidDict
[_PcdGuidString
.upper()] = FfsFile
844 EdkLogger
.error("build",
846 "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile
.CurrentLineNum
,
847 FfsFile
.CurrentLineContent
,
848 _GuidDict
[_PcdGuidString
.upper()].CurrentLineNum
,
849 _GuidDict
[_PcdGuidString
.upper()].CurrentLineContent
,
850 FfsFile
.NameGuid
.upper()),
851 ExtraData
=self
.FdfFile
)
853 if FfsFile
.NameGuid
.upper() not in _GuidDict
:
854 _GuidDict
[FfsFile
.NameGuid
.upper()] = FfsFile
857 # Two raw file GUID conflict.
859 EdkLogger
.error("build",
861 "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile
.CurrentLineNum
,
862 FfsFile
.CurrentLineContent
,
863 _GuidDict
[FfsFile
.NameGuid
.upper()].CurrentLineNum
,
864 _GuidDict
[FfsFile
.NameGuid
.upper()].CurrentLineContent
,
865 FfsFile
.NameGuid
.upper()),
866 ExtraData
=self
.FdfFile
)
869 def _CheckPcdDefineAndType(self
):
871 TAB_PCDS_FIXED_AT_BUILD
, TAB_PCDS_PATCHABLE_IN_MODULE
, TAB_PCDS_FEATURE_FLAG
,
872 TAB_PCDS_DYNAMIC
, #TAB_PCDS_DYNAMIC_HII, TAB_PCDS_DYNAMIC_VPD,
873 TAB_PCDS_DYNAMIC_EX
, # TAB_PCDS_DYNAMIC_EX_HII, TAB_PCDS_DYNAMIC_EX_VPD
876 # This dict store PCDs which are not used by any modules with specified arches
877 UnusedPcd
= OrderedDict()
878 for Pa
in self
.AutoGenObjectList
:
879 # Key of DSC's Pcds dictionary is PcdCName, TokenSpaceGuid
880 for Pcd
in Pa
.Platform
.Pcds
:
881 PcdType
= Pa
.Platform
.Pcds
[Pcd
].Type
883 # If no PCD type, this PCD comes from FDF
887 # Try to remove Hii and Vpd suffix
888 if PcdType
.startswith(TAB_PCDS_DYNAMIC_EX
):
889 PcdType
= TAB_PCDS_DYNAMIC_EX
890 elif PcdType
.startswith(TAB_PCDS_DYNAMIC
):
891 PcdType
= TAB_PCDS_DYNAMIC
893 for Package
in Pa
.PackageList
:
894 # Key of DEC's Pcds dictionary is PcdCName, TokenSpaceGuid, PcdType
895 if (Pcd
[0], Pcd
[1], PcdType
) in Package
.Pcds
:
897 for Type
in PcdTypeList
:
898 if (Pcd
[0], Pcd
[1], Type
) in Package
.Pcds
:
902 "Type [%s] of PCD [%s.%s] in DSC file doesn't match the type [%s] defined in DEC file." \
903 % (Pa
.Platform
.Pcds
[Pcd
].Type
, Pcd
[1], Pcd
[0], Type
),
908 UnusedPcd
.setdefault(Pcd
, []).append(Pa
.Arch
)
910 for Pcd
in UnusedPcd
:
913 "The PCD was not specified by any INF module in the platform for the given architecture.\n"
914 "\tPCD: [%s.%s]\n\tPlatform: [%s]\n\tArch: %s"
915 % (Pcd
[1], Pcd
[0], os
.path
.basename(str(self
.MetaFile
)), str(UnusedPcd
[Pcd
])),
920 return "%s [%s]" % (self
.MetaFile
, ", ".join(self
.ArchList
))
922 ## Return the directory to store FV files
924 if self
._FvDir
is None:
925 self
._FvDir
= path
.join(self
.BuildDir
, TAB_FV_DIRECTORY
)
928 ## Return the directory to store all intermediate and final files built
929 def _GetBuildDir(self
):
930 if self
._BuildDir
is None:
931 return self
.AutoGenObjectList
[0].BuildDir
933 ## Return the build output directory platform specifies
934 def _GetOutputDir(self
):
935 return self
.Platform
.OutputDirectory
937 ## Return platform name
939 return self
.Platform
.PlatformName
941 ## Return meta-file GUID
943 return self
.Platform
.Guid
945 ## Return platform version
946 def _GetVersion(self
):
947 return self
.Platform
.Version
949 ## Return paths of tools
950 def _GetToolDefinition(self
):
951 return self
.AutoGenObjectList
[0].ToolDefinition
953 ## Return directory of platform makefile
955 # @retval string Makefile directory
957 def _GetMakeFileDir(self
):
958 if self
._MakeFileDir
is None:
959 self
._MakeFileDir
= self
.BuildDir
960 return self
._MakeFileDir
962 ## Return build command string
964 # @retval string Build command string
966 def _GetBuildCommand(self
):
967 if self
._BuildCommand
is None:
968 # BuildCommand should be all the same. So just get one from platform AutoGen
969 self
._BuildCommand
= self
.AutoGenObjectList
[0].BuildCommand
970 return self
._BuildCommand
972 ## Check the PCDs token value conflict in each DEC file.
974 # Will cause build break and raise error message while two PCDs conflict.
978 def _CheckAllPcdsTokenValueConflict(self
):
979 for Pa
in self
.AutoGenObjectList
:
980 for Package
in Pa
.PackageList
:
981 PcdList
= Package
.Pcds
.values()
982 PcdList
.sort(lambda x
, y
: cmp(int(x
.TokenValue
, 0), int(y
.TokenValue
, 0)))
984 while (Count
< len(PcdList
) - 1) :
985 Item
= PcdList
[Count
]
986 ItemNext
= PcdList
[Count
+ 1]
988 # Make sure in the same token space the TokenValue should be unique
990 if (int(Item
.TokenValue
, 0) == int(ItemNext
.TokenValue
, 0)):
991 SameTokenValuePcdList
= []
992 SameTokenValuePcdList
.append(Item
)
993 SameTokenValuePcdList
.append(ItemNext
)
994 RemainPcdListLength
= len(PcdList
) - Count
- 2
995 for ValueSameCount
in range(RemainPcdListLength
):
996 if int(PcdList
[len(PcdList
) - RemainPcdListLength
+ ValueSameCount
].TokenValue
, 0) == int(Item
.TokenValue
, 0):
997 SameTokenValuePcdList
.append(PcdList
[len(PcdList
) - RemainPcdListLength
+ ValueSameCount
])
1001 # Sort same token value PCD list with TokenGuid and TokenCName
1003 SameTokenValuePcdList
.sort(lambda x
, y
: cmp("%s.%s" % (x
.TokenSpaceGuidCName
, x
.TokenCName
), "%s.%s" % (y
.TokenSpaceGuidCName
, y
.TokenCName
)))
1004 SameTokenValuePcdListCount
= 0
1005 while (SameTokenValuePcdListCount
< len(SameTokenValuePcdList
) - 1):
1007 TemListItem
= SameTokenValuePcdList
[SameTokenValuePcdListCount
]
1008 TemListItemNext
= SameTokenValuePcdList
[SameTokenValuePcdListCount
+ 1]
1010 if (TemListItem
.TokenSpaceGuidCName
== TemListItemNext
.TokenSpaceGuidCName
) and (TemListItem
.TokenCName
!= TemListItemNext
.TokenCName
):
1011 for PcdItem
in GlobalData
.MixedPcd
:
1012 if (TemListItem
.TokenCName
, TemListItem
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
] or \
1013 (TemListItemNext
.TokenCName
, TemListItemNext
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
1019 "The TokenValue [%s] of PCD [%s.%s] is conflict with: [%s.%s] in %s"\
1020 % (TemListItem
.TokenValue
, TemListItem
.TokenSpaceGuidCName
, TemListItem
.TokenCName
, TemListItemNext
.TokenSpaceGuidCName
, TemListItemNext
.TokenCName
, Package
),
1023 SameTokenValuePcdListCount
+= 1
1024 Count
+= SameTokenValuePcdListCount
1027 PcdList
= Package
.Pcds
.values()
1028 PcdList
.sort(lambda x
, y
: cmp("%s.%s" % (x
.TokenSpaceGuidCName
, x
.TokenCName
), "%s.%s" % (y
.TokenSpaceGuidCName
, y
.TokenCName
)))
1030 while (Count
< len(PcdList
) - 1) :
1031 Item
= PcdList
[Count
]
1032 ItemNext
= PcdList
[Count
+ 1]
1034 # Check PCDs with same TokenSpaceGuidCName.TokenCName have same token value as well.
1036 if (Item
.TokenSpaceGuidCName
== ItemNext
.TokenSpaceGuidCName
) and (Item
.TokenCName
== ItemNext
.TokenCName
) and (int(Item
.TokenValue
, 0) != int(ItemNext
.TokenValue
, 0)):
1040 "The TokenValue [%s] of PCD [%s.%s] in %s defined in two places should be same as well."\
1041 % (Item
.TokenValue
, Item
.TokenSpaceGuidCName
, Item
.TokenCName
, Package
),
1045 ## Generate fds command
1046 def _GenFdsCommand(self
):
1047 return (GenMake
.TopLevelMakefile(self
)._TEMPLATE
_.Replace(GenMake
.TopLevelMakefile(self
)._TemplateDict
)).strip()
1049 ## Create makefile for the platform and modules in it
1051 # @param CreateDepsMakeFile Flag indicating if the makefile for
1052 # modules will be created as well
1054 def CreateMakeFile(self
, CreateDepsMakeFile
=False):
1055 if CreateDepsMakeFile
:
1056 for Pa
in self
.AutoGenObjectList
:
1057 Pa
.CreateMakeFile(CreateDepsMakeFile
)
1059 ## Create autogen code for platform and modules
1061 # Since there's no autogen code for platform, this method will do nothing
1062 # if CreateModuleCodeFile is set to False.
1064 # @param CreateDepsCodeFile Flag indicating if creating module's
1065 # autogen code file or not
1067 def CreateCodeFile(self
, CreateDepsCodeFile
=False):
1068 if not CreateDepsCodeFile
:
1070 for Pa
in self
.AutoGenObjectList
:
1071 Pa
.CreateCodeFile(CreateDepsCodeFile
)
1073 ## Create AsBuilt INF file the platform
1075 def CreateAsBuiltInf(self
):
1078 Name
= property(_GetName
)
1079 Guid
= property(_GetGuid
)
1080 Version
= property(_GetVersion
)
1081 OutputDir
= property(_GetOutputDir
)
1083 ToolDefinition
= property(_GetToolDefinition
) # toolcode : tool path
1085 BuildDir
= property(_GetBuildDir
)
1086 FvDir
= property(_GetFvDir
)
1087 MakeFileDir
= property(_GetMakeFileDir
)
1088 BuildCommand
= property(_GetBuildCommand
)
1089 GenFdsCommand
= property(_GenFdsCommand
)
1091 ## AutoGen class for platform
1093 # PlatformAutoGen class will process the original information in platform
1094 # file in order to generate makefile for platform.
1096 class PlatformAutoGen(AutoGen
):
1097 # call super().__init__ then call the worker function with different parameter count
1098 def __init__(self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
1102 super(PlatformAutoGen
, self
).__init
__(self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
)
1103 self
._InitWorker
(Workspace
, MetaFile
, Target
, Toolchain
, Arch
)
1106 # Used to store all PCDs for both PEI and DXE phase, in order to generate
1107 # correct PCD database
1110 _NonDynaPcdList_
= []
1114 # The priority list while override build option
1116 PrioList
= {"0x11111" : 16, # TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE (Highest)
1117 "0x01111" : 15, # ******_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
1118 "0x10111" : 14, # TARGET_*********_ARCH_COMMANDTYPE_ATTRIBUTE
1119 "0x00111" : 13, # ******_*********_ARCH_COMMANDTYPE_ATTRIBUTE
1120 "0x11011" : 12, # TARGET_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE
1121 "0x01011" : 11, # ******_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE
1122 "0x10011" : 10, # TARGET_*********_****_COMMANDTYPE_ATTRIBUTE
1123 "0x00011" : 9, # ******_*********_****_COMMANDTYPE_ATTRIBUTE
1124 "0x11101" : 8, # TARGET_TOOLCHAIN_ARCH_***********_ATTRIBUTE
1125 "0x01101" : 7, # ******_TOOLCHAIN_ARCH_***********_ATTRIBUTE
1126 "0x10101" : 6, # TARGET_*********_ARCH_***********_ATTRIBUTE
1127 "0x00101" : 5, # ******_*********_ARCH_***********_ATTRIBUTE
1128 "0x11001" : 4, # TARGET_TOOLCHAIN_****_***********_ATTRIBUTE
1129 "0x01001" : 3, # ******_TOOLCHAIN_****_***********_ATTRIBUTE
1130 "0x10001" : 2, # TARGET_*********_****_***********_ATTRIBUTE
1131 "0x00001" : 1} # ******_*********_****_***********_ATTRIBUTE (Lowest)
1133 ## Initialize PlatformAutoGen
1136 # @param Workspace WorkspaceAutoGen object
1137 # @param PlatformFile Platform file (DSC file)
1138 # @param Target Build target (DEBUG, RELEASE)
1139 # @param Toolchain Name of tool chain
1140 # @param Arch arch of the platform supports
1142 def _InitWorker(self
, Workspace
, PlatformFile
, Target
, Toolchain
, Arch
):
1143 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "AutoGen platform [%s] [%s]" % (PlatformFile
, Arch
))
1144 GlobalData
.gProcessingFile
= "%s [%s, %s, %s]" % (PlatformFile
, Arch
, Toolchain
, Target
)
1146 self
.MetaFile
= PlatformFile
1147 self
.Workspace
= Workspace
1148 self
.WorkspaceDir
= Workspace
.WorkspaceDir
1149 self
.ToolChain
= Toolchain
1150 self
.BuildTarget
= Target
1152 self
.SourceDir
= PlatformFile
.SubDir
1153 self
.SourceOverrideDir
= None
1154 self
.FdTargetList
= self
.Workspace
.FdTargetList
1155 self
.FvTargetList
= self
.Workspace
.FvTargetList
1156 self
.AllPcdList
= []
1157 # get the original module/package/platform objects
1158 self
.BuildDatabase
= Workspace
.BuildDatabase
1159 self
.DscBuildDataObj
= Workspace
.Platform
1160 self
._GuidDict
= Workspace
._GuidDict
1162 # flag indicating if the makefile/C-code file has been created or not
1163 self
.IsMakeFileCreated
= False
1164 self
.IsCodeFileCreated
= False
1166 self
._Platform
= None
1169 self
._Version
= None
1171 self
._BuildRule
= None
1172 self
._SourceDir
= None
1173 self
._BuildDir
= None
1174 self
._OutputDir
= None
1176 self
._MakeFileDir
= None
1177 self
._FdfFile
= None
1179 self
._PcdTokenNumber
= None # (TokenCName, TokenSpaceGuidCName) : GeneratedTokenNumber
1180 self
._DynamicPcdList
= None # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
1181 self
._NonDynamicPcdList
= None # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
1182 self
._NonDynamicPcdDict
= {}
1184 self
._ToolDefinitions
= None
1185 self
._ToolDefFile
= None # toolcode : tool path
1186 self
._ToolChainFamily
= None
1187 self
._BuildRuleFamily
= None
1188 self
._BuildOption
= None # toolcode : option
1189 self
._EdkBuildOption
= None # edktoolcode : option
1190 self
._EdkIIBuildOption
= None # edkiitoolcode : option
1191 self
._PackageList
= None
1192 self
._ModuleAutoGenList
= None
1193 self
._LibraryAutoGenList
= None
1194 self
._BuildCommand
= None
1195 self
._AsBuildInfList
= []
1196 self
._AsBuildModuleList
= []
1198 self
.VariableInfo
= None
1200 if GlobalData
.gFdfParser
is not None:
1201 self
._AsBuildInfList
= GlobalData
.gFdfParser
.Profile
.InfList
1202 for Inf
in self
._AsBuildInfList
:
1203 InfClass
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, self
.Arch
)
1204 M
= self
.BuildDatabase
[InfClass
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1205 if not M
.IsSupportedArch
:
1207 self
._AsBuildModuleList
.append(InfClass
)
1208 # get library/modules for build
1209 self
.LibraryBuildDirectoryList
= []
1210 self
.ModuleBuildDirectoryList
= []
1215 return "%s [%s]" % (self
.MetaFile
, self
.Arch
)
1217 ## Create autogen code for platform and modules
1219 # Since there's no autogen code for platform, this method will do nothing
1220 # if CreateModuleCodeFile is set to False.
1222 # @param CreateModuleCodeFile Flag indicating if creating module's
1223 # autogen code file or not
1225 def CreateCodeFile(self
, CreateModuleCodeFile
=False):
1226 # only module has code to be greated, so do nothing if CreateModuleCodeFile is False
1227 if self
.IsCodeFileCreated
or not CreateModuleCodeFile
:
1230 for Ma
in self
.ModuleAutoGenList
:
1231 Ma
.CreateCodeFile(True)
1233 # don't do this twice
1234 self
.IsCodeFileCreated
= True
1236 ## Generate Fds Command
1237 def _GenFdsCommand(self
):
1238 return self
.Workspace
.GenFdsCommand
1240 ## Create makefile for the platform and mdoules in it
1242 # @param CreateModuleMakeFile Flag indicating if the makefile for
1243 # modules will be created as well
1245 def CreateMakeFile(self
, CreateModuleMakeFile
=False, FfsCommand
= {}):
1246 if CreateModuleMakeFile
:
1247 for ModuleFile
in self
.Platform
.Modules
:
1248 Ma
= ModuleAutoGen(self
.Workspace
, ModuleFile
, self
.BuildTarget
,
1249 self
.ToolChain
, self
.Arch
, self
.MetaFile
)
1250 if (ModuleFile
.File
, self
.Arch
) in FfsCommand
:
1251 Ma
.CreateMakeFile(True, FfsCommand
[ModuleFile
.File
, self
.Arch
])
1253 Ma
.CreateMakeFile(True)
1254 #Ma.CreateAsBuiltInf()
1256 # no need to create makefile for the platform more than once
1257 if self
.IsMakeFileCreated
:
1260 # create library/module build dirs for platform
1261 Makefile
= GenMake
.PlatformMakefile(self
)
1262 self
.LibraryBuildDirectoryList
= Makefile
.GetLibraryBuildDirectoryList()
1263 self
.ModuleBuildDirectoryList
= Makefile
.GetModuleBuildDirectoryList()
1265 self
.IsMakeFileCreated
= True
1267 ## Deal with Shared FixedAtBuild Pcds
1269 def CollectFixedAtBuildPcds(self
):
1270 for LibAuto
in self
.LibraryAutoGenList
:
1271 FixedAtBuildPcds
= {}
1272 ShareFixedAtBuildPcdsSameValue
= {}
1273 for Module
in LibAuto
._ReferenceModules
:
1274 for Pcd
in Module
.FixedAtBuildPcds
+ LibAuto
.FixedAtBuildPcds
:
1275 key
= ".".join((Pcd
.TokenSpaceGuidCName
,Pcd
.TokenCName
))
1276 if key
not in FixedAtBuildPcds
:
1277 ShareFixedAtBuildPcdsSameValue
[key
] = True
1278 FixedAtBuildPcds
[key
] = Pcd
.DefaultValue
1280 if FixedAtBuildPcds
[key
] != Pcd
.DefaultValue
:
1281 ShareFixedAtBuildPcdsSameValue
[key
] = False
1282 for Pcd
in LibAuto
.FixedAtBuildPcds
:
1283 key
= ".".join((Pcd
.TokenSpaceGuidCName
,Pcd
.TokenCName
))
1284 if (Pcd
.TokenCName
,Pcd
.TokenSpaceGuidCName
) not in self
.NonDynamicPcdDict
:
1287 DscPcd
= self
.NonDynamicPcdDict
[(Pcd
.TokenCName
,Pcd
.TokenSpaceGuidCName
)]
1288 if DscPcd
.Type
!= TAB_PCDS_FIXED_AT_BUILD
:
1290 if key
in ShareFixedAtBuildPcdsSameValue
and ShareFixedAtBuildPcdsSameValue
[key
]:
1291 LibAuto
.ConstPcd
[key
] = FixedAtBuildPcds
[key
]
1293 def CollectVariables(self
, DynamicPcdSet
):
1297 if self
.Workspace
.FdfFile
:
1298 FdDict
= self
.Workspace
.FdfProfile
.FdDict
[GlobalData
.gFdfParser
.CurrentFdName
]
1299 for FdRegion
in FdDict
.RegionList
:
1300 for item
in FdRegion
.RegionDataList
:
1301 if self
.Platform
.VpdToolGuid
.strip() and self
.Platform
.VpdToolGuid
in item
:
1302 VpdRegionSize
= FdRegion
.Size
1303 VpdRegionBase
= FdRegion
.Offset
1307 VariableInfo
= VariableMgr(self
.DscBuildDataObj
._GetDefaultStores
(),self
.DscBuildDataObj
._GetSkuIds
())
1308 VariableInfo
.SetVpdRegionMaxSize(VpdRegionSize
)
1309 VariableInfo
.SetVpdRegionOffset(VpdRegionBase
)
1311 for Pcd
in DynamicPcdSet
:
1312 pcdname
= ".".join((Pcd
.TokenSpaceGuidCName
,Pcd
.TokenCName
))
1313 for SkuName
in Pcd
.SkuInfoList
:
1314 Sku
= Pcd
.SkuInfoList
[SkuName
]
1316 if SkuId
is None or SkuId
== '':
1318 if len(Sku
.VariableName
) > 0:
1319 VariableGuidStructure
= Sku
.VariableGuidValue
1320 VariableGuid
= GuidStructureStringToGuidString(VariableGuidStructure
)
1321 for StorageName
in Sku
.DefaultStoreDict
:
1322 VariableInfo
.append_variable(var_info(Index
,pcdname
,StorageName
,SkuName
, StringToArray(Sku
.VariableName
),VariableGuid
, Sku
.VariableOffset
, Sku
.VariableAttribute
, Sku
.HiiDefaultValue
,Sku
.DefaultStoreDict
[StorageName
],Pcd
.DatumType
))
1326 def UpdateNVStoreMaxSize(self
,OrgVpdFile
):
1327 if self
.VariableInfo
:
1328 VpdMapFilePath
= os
.path
.join(self
.BuildDir
, TAB_FV_DIRECTORY
, "%s.map" % self
.Platform
.VpdToolGuid
)
1329 PcdNvStoreDfBuffer
= [item
for item
in self
._DynamicPcdList
if item
.TokenCName
== "PcdNvStoreDefaultValueBuffer" and item
.TokenSpaceGuidCName
== "gEfiMdeModulePkgTokenSpaceGuid"]
1331 if PcdNvStoreDfBuffer
:
1332 if os
.path
.exists(VpdMapFilePath
):
1333 OrgVpdFile
.Read(VpdMapFilePath
)
1334 PcdItems
= OrgVpdFile
.GetOffset(PcdNvStoreDfBuffer
[0])
1335 NvStoreOffset
= PcdItems
.values()[0].strip() if PcdItems
else '0'
1337 EdkLogger
.error("build", FILE_READ_FAILURE
, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath
)
1339 NvStoreOffset
= int(NvStoreOffset
,16) if NvStoreOffset
.upper().startswith("0X") else int(NvStoreOffset
)
1340 default_skuobj
= PcdNvStoreDfBuffer
[0].SkuInfoList
.get(TAB_DEFAULT
)
1341 maxsize
= self
.VariableInfo
.VpdRegionSize
- NvStoreOffset
if self
.VariableInfo
.VpdRegionSize
else len(default_skuobj
.DefaultValue
.split(","))
1342 var_data
= self
.VariableInfo
.PatchNVStoreDefaultMaxSize(maxsize
)
1344 if var_data
and default_skuobj
:
1345 default_skuobj
.DefaultValue
= var_data
1346 PcdNvStoreDfBuffer
[0].DefaultValue
= var_data
1347 PcdNvStoreDfBuffer
[0].SkuInfoList
.clear()
1348 PcdNvStoreDfBuffer
[0].SkuInfoList
[TAB_DEFAULT
] = default_skuobj
1349 PcdNvStoreDfBuffer
[0].MaxDatumSize
= str(len(default_skuobj
.DefaultValue
.split(",")))
1353 ## Collect dynamic PCDs
1355 # Gather dynamic PCDs list from each module and their settings from platform
1356 # This interface should be invoked explicitly when platform action is created.
1358 def CollectPlatformDynamicPcds(self
):
1360 for key
in self
.Platform
.Pcds
:
1361 for SinglePcd
in GlobalData
.MixedPcd
:
1362 if (self
.Platform
.Pcds
[key
].TokenCName
, self
.Platform
.Pcds
[key
].TokenSpaceGuidCName
) == SinglePcd
:
1363 for item
in GlobalData
.MixedPcd
[SinglePcd
]:
1364 Pcd_Type
= item
[0].split('_')[-1]
1365 if (Pcd_Type
== self
.Platform
.Pcds
[key
].Type
) or (Pcd_Type
== TAB_PCDS_DYNAMIC_EX
and self
.Platform
.Pcds
[key
].Type
in PCD_DYNAMIC_EX_TYPE_SET
) or \
1366 (Pcd_Type
== TAB_PCDS_DYNAMIC
and self
.Platform
.Pcds
[key
].Type
in PCD_DYNAMIC_TYPE_SET
):
1367 Value
= self
.Platform
.Pcds
[key
]
1368 Value
.TokenCName
= self
.Platform
.Pcds
[key
].TokenCName
+ '_' + Pcd_Type
1370 newkey
= (Value
.TokenCName
, key
[1])
1372 newkey
= (Value
.TokenCName
, key
[1], key
[2])
1373 del self
.Platform
.Pcds
[key
]
1374 self
.Platform
.Pcds
[newkey
] = Value
1382 # for gathering error information
1383 NoDatumTypePcdList
= set()
1385 for InfName
in self
._AsBuildInfList
:
1386 InfName
= mws
.join(self
.WorkspaceDir
, InfName
)
1387 FdfModuleList
.append(os
.path
.normpath(InfName
))
1388 for F
in self
.Platform
.Modules
.keys():
1389 M
= ModuleAutoGen(self
.Workspace
, F
, self
.BuildTarget
, self
.ToolChain
, self
.Arch
, self
.MetaFile
)
1390 #GuidValue.update(M.Guids)
1392 self
.Platform
.Modules
[F
].M
= M
1394 for PcdFromModule
in M
.ModulePcdList
+ M
.LibraryPcdList
:
1395 # make sure that the "VOID*" kind of datum has MaxDatumSize set
1396 if PcdFromModule
.DatumType
== TAB_VOID
and not PcdFromModule
.MaxDatumSize
:
1397 NoDatumTypePcdList
.add("%s.%s [%s]" % (PcdFromModule
.TokenSpaceGuidCName
, PcdFromModule
.TokenCName
, F
))
1399 # Check the PCD from Binary INF or Source INF
1400 if M
.IsBinaryModule
== True:
1401 PcdFromModule
.IsFromBinaryInf
= True
1403 # Check the PCD from DSC or not
1404 PcdFromModule
.IsFromDsc
= (PcdFromModule
.TokenCName
, PcdFromModule
.TokenSpaceGuidCName
) in self
.Platform
.Pcds
1406 if PcdFromModule
.Type
in PCD_DYNAMIC_TYPE_SET
or PcdFromModule
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
1407 if F
.Path
not in FdfModuleList
:
1408 # If one of the Source built modules listed in the DSC is not listed
1409 # in FDF modules, and the INF lists a PCD can only use the PcdsDynamic
1410 # access method (it is only listed in the DEC file that declares the
1411 # PCD as PcdsDynamic), then build tool will report warning message
1412 # notify the PI that they are attempting to build a module that must
1413 # be included in a flash image in order to be functional. These Dynamic
1414 # PCD will not be added into the Database unless it is used by other
1415 # modules that are included in the FDF file.
1416 if PcdFromModule
.Type
in PCD_DYNAMIC_TYPE_SET
and \
1417 PcdFromModule
.IsFromBinaryInf
== False:
1418 # Print warning message to let the developer make a determine.
1420 # If one of the Source built modules listed in the DSC is not listed in
1421 # FDF modules, and the INF lists a PCD can only use the PcdsDynamicEx
1422 # access method (it is only listed in the DEC file that declares the
1423 # PCD as PcdsDynamicEx), then DO NOT break the build; DO NOT add the
1424 # PCD to the Platform's PCD Database.
1425 if PcdFromModule
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
1428 # If a dynamic PCD used by a PEM module/PEI module & DXE module,
1429 # it should be stored in Pcd PEI database, If a dynamic only
1430 # used by DXE module, it should be stored in DXE PCD database.
1431 # The default Phase is DXE
1433 if M
.ModuleType
in SUP_MODULE_SET_PEI
:
1434 PcdFromModule
.Phase
= "PEI"
1435 if PcdFromModule
not in self
._DynaPcdList
_:
1436 self
._DynaPcdList
_.append(PcdFromModule
)
1437 elif PcdFromModule
.Phase
== 'PEI':
1438 # overwrite any the same PCD existing, if Phase is PEI
1439 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1440 self
._DynaPcdList
_[Index
] = PcdFromModule
1441 elif PcdFromModule
not in self
._NonDynaPcdList
_:
1442 self
._NonDynaPcdList
_.append(PcdFromModule
)
1443 elif PcdFromModule
in self
._NonDynaPcdList
_ and PcdFromModule
.IsFromBinaryInf
== True:
1444 Index
= self
._NonDynaPcdList
_.index(PcdFromModule
)
1445 if self
._NonDynaPcdList
_[Index
].IsFromBinaryInf
== False:
1446 #The PCD from Binary INF will override the same one from source INF
1447 self
._NonDynaPcdList
_.remove (self
._NonDynaPcdList
_[Index
])
1448 PcdFromModule
.Pending
= False
1449 self
._NonDynaPcdList
_.append (PcdFromModule
)
1450 DscModuleSet
= {os
.path
.normpath(ModuleInf
.Path
) for ModuleInf
in self
.Platform
.Modules
}
1451 # add the PCD from modules that listed in FDF but not in DSC to Database
1452 for InfName
in FdfModuleList
:
1453 if InfName
not in DscModuleSet
:
1454 InfClass
= PathClass(InfName
)
1455 M
= self
.BuildDatabase
[InfClass
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1456 # If a module INF in FDF but not in current arch's DSC module list, it must be module (either binary or source)
1457 # for different Arch. PCDs in source module for different Arch is already added before, so skip the source module here.
1458 # For binary module, if in current arch, we need to list the PCDs into database.
1459 if not M
.IsSupportedArch
:
1461 # Override the module PCD setting by platform setting
1462 ModulePcdList
= self
.ApplyPcdSetting(M
, M
.Pcds
)
1463 for PcdFromModule
in ModulePcdList
:
1464 PcdFromModule
.IsFromBinaryInf
= True
1465 PcdFromModule
.IsFromDsc
= False
1466 # Only allow the DynamicEx and Patchable PCD in AsBuild INF
1467 if PcdFromModule
.Type
not in PCD_DYNAMIC_EX_TYPE_SET
and PcdFromModule
.Type
not in TAB_PCDS_PATCHABLE_IN_MODULE
:
1468 EdkLogger
.error("build", AUTOGEN_ERROR
, "PCD setting error",
1470 ExtraData
="\n\tExisted %s PCD %s in:\n\t\t%s\n"
1471 % (PcdFromModule
.Type
, PcdFromModule
.TokenCName
, InfName
))
1472 # make sure that the "VOID*" kind of datum has MaxDatumSize set
1473 if PcdFromModule
.DatumType
== TAB_VOID
and not PcdFromModule
.MaxDatumSize
:
1474 NoDatumTypePcdList
.add("%s.%s [%s]" % (PcdFromModule
.TokenSpaceGuidCName
, PcdFromModule
.TokenCName
, InfName
))
1475 if M
.ModuleType
in SUP_MODULE_SET_PEI
:
1476 PcdFromModule
.Phase
= "PEI"
1477 if PcdFromModule
not in self
._DynaPcdList
_ and PcdFromModule
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
1478 self
._DynaPcdList
_.append(PcdFromModule
)
1479 elif PcdFromModule
not in self
._NonDynaPcdList
_ and PcdFromModule
.Type
in TAB_PCDS_PATCHABLE_IN_MODULE
:
1480 self
._NonDynaPcdList
_.append(PcdFromModule
)
1481 if PcdFromModule
in self
._DynaPcdList
_ and PcdFromModule
.Phase
== 'PEI' and PcdFromModule
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
1482 # Overwrite the phase of any the same PCD existing, if Phase is PEI.
1483 # It is to solve the case that a dynamic PCD used by a PEM module/PEI
1484 # module & DXE module at a same time.
1485 # Overwrite the type of the PCDs in source INF by the type of AsBuild
1486 # INF file as DynamicEx.
1487 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1488 self
._DynaPcdList
_[Index
].Phase
= PcdFromModule
.Phase
1489 self
._DynaPcdList
_[Index
].Type
= PcdFromModule
.Type
1490 for PcdFromModule
in self
._NonDynaPcdList
_:
1491 # If a PCD is not listed in the DSC file, but binary INF files used by
1492 # this platform all (that use this PCD) list the PCD in a [PatchPcds]
1493 # section, AND all source INF files used by this platform the build
1494 # that use the PCD list the PCD in either a [Pcds] or [PatchPcds]
1495 # section, then the tools must NOT add the PCD to the Platform's PCD
1496 # Database; the build must assign the access method for this PCD as
1497 # PcdsPatchableInModule.
1498 if PcdFromModule
not in self
._DynaPcdList
_:
1500 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1501 if PcdFromModule
.IsFromDsc
== False and \
1502 PcdFromModule
.Type
in TAB_PCDS_PATCHABLE_IN_MODULE
and \
1503 PcdFromModule
.IsFromBinaryInf
== True and \
1504 self
._DynaPcdList
_[Index
].IsFromBinaryInf
== False:
1505 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1506 self
._DynaPcdList
_.remove (self
._DynaPcdList
_[Index
])
1508 # print out error information and break the build, if error found
1509 if len(NoDatumTypePcdList
) > 0:
1510 NoDatumTypePcdListString
= "\n\t\t".join(NoDatumTypePcdList
)
1511 EdkLogger
.error("build", AUTOGEN_ERROR
, "PCD setting error",
1513 ExtraData
="\n\tPCD(s) without MaxDatumSize:\n\t\t%s\n"
1514 % NoDatumTypePcdListString
)
1515 self
._NonDynamicPcdList
= self
._NonDynaPcdList
_
1516 self
._DynamicPcdList
= self
._DynaPcdList
_
1518 # Sort dynamic PCD list to:
1519 # 1) If PCD's datum type is VOID* and value is unicode string which starts with L, the PCD item should
1520 # try to be put header of dynamicd List
1521 # 2) If PCD is HII type, the PCD item should be put after unicode type PCD
1523 # The reason of sorting is make sure the unicode string is in double-byte alignment in string table.
1525 UnicodePcdArray
= set()
1527 OtherPcdArray
= set()
1529 VpdFile
= VpdInfoFile
.VpdInfoFile()
1530 NeedProcessVpdMapFile
= False
1532 for pcd
in self
.Platform
.Pcds
:
1533 if pcd
not in self
._PlatformPcds
:
1534 self
._PlatformPcds
[pcd
] = self
.Platform
.Pcds
[pcd
]
1536 for item
in self
._PlatformPcds
:
1537 if self
._PlatformPcds
[item
].DatumType
and self
._PlatformPcds
[item
].DatumType
not in [TAB_UINT8
, TAB_UINT16
, TAB_UINT32
, TAB_UINT64
, TAB_VOID
, "BOOLEAN"]:
1538 self
._PlatformPcds
[item
].DatumType
= TAB_VOID
1540 if (self
.Workspace
.ArchList
[-1] == self
.Arch
):
1541 for Pcd
in self
._DynamicPcdList
:
1542 # just pick the a value to determine whether is unicode string type
1543 Sku
= Pcd
.SkuInfoList
.values()[0]
1544 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1546 if Pcd
.DatumType
not in [TAB_UINT8
, TAB_UINT16
, TAB_UINT32
, TAB_UINT64
, TAB_VOID
, "BOOLEAN"]:
1547 Pcd
.DatumType
= TAB_VOID
1549 # if found PCD which datum value is unicode string the insert to left size of UnicodeIndex
1550 # if found HII type PCD then insert to right of UnicodeIndex
1551 if Pcd
.Type
in [TAB_PCDS_DYNAMIC_VPD
, TAB_PCDS_DYNAMIC_EX_VPD
]:
1552 VpdPcdDict
[(Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
)] = Pcd
1554 #Collect DynamicHii PCD values and assign it to DynamicExVpd PCD gEfiMdeModulePkgTokenSpaceGuid.PcdNvStoreDefaultValueBuffer
1555 PcdNvStoreDfBuffer
= VpdPcdDict
.get(("PcdNvStoreDefaultValueBuffer","gEfiMdeModulePkgTokenSpaceGuid"))
1556 if PcdNvStoreDfBuffer
:
1557 self
.VariableInfo
= self
.CollectVariables(self
._DynamicPcdList
)
1558 vardump
= self
.VariableInfo
.dump()
1560 PcdNvStoreDfBuffer
.DefaultValue
= vardump
1561 for skuname
in PcdNvStoreDfBuffer
.SkuInfoList
:
1562 PcdNvStoreDfBuffer
.SkuInfoList
[skuname
].DefaultValue
= vardump
1563 PcdNvStoreDfBuffer
.MaxDatumSize
= str(len(vardump
.split(",")))
1565 PlatformPcds
= self
._PlatformPcds
.keys()
1568 # Add VPD type PCD into VpdFile and determine whether the VPD PCD need to be fixed up.
1571 for PcdKey
in PlatformPcds
:
1572 Pcd
= self
._PlatformPcds
[PcdKey
]
1573 if Pcd
.Type
in [TAB_PCDS_DYNAMIC_VPD
, TAB_PCDS_DYNAMIC_EX_VPD
] and \
1574 PcdKey
in VpdPcdDict
:
1575 Pcd
= VpdPcdDict
[PcdKey
]
1577 DefaultSku
= Pcd
.SkuInfoList
.get(TAB_DEFAULT
)
1579 PcdValue
= DefaultSku
.DefaultValue
1580 if PcdValue
not in SkuValueMap
:
1581 SkuValueMap
[PcdValue
] = []
1582 VpdFile
.Add(Pcd
, TAB_DEFAULT
,DefaultSku
.VpdOffset
)
1583 SkuValueMap
[PcdValue
].append(DefaultSku
)
1585 for (SkuName
,Sku
) in Pcd
.SkuInfoList
.items():
1586 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1587 PcdValue
= Sku
.DefaultValue
1589 PcdValue
= Pcd
.DefaultValue
1590 if Sku
.VpdOffset
!= '*':
1591 if PcdValue
.startswith("{"):
1593 elif PcdValue
.startswith("L"):
1598 VpdOffset
= int(Sku
.VpdOffset
)
1601 VpdOffset
= int(Sku
.VpdOffset
, 16)
1603 EdkLogger
.error("build", FORMAT_INVALID
, "Invalid offset value %s for PCD %s.%s." % (Sku
.VpdOffset
, Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
))
1604 if VpdOffset
% Alignment
!= 0:
1605 if PcdValue
.startswith("{"):
1606 EdkLogger
.warn("build", "The offset value of PCD %s.%s is not 8-byte aligned!" %(Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
), File
=self
.MetaFile
)
1608 EdkLogger
.error("build", FORMAT_INVALID
, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
, Alignment
))
1609 if PcdValue
not in SkuValueMap
:
1610 SkuValueMap
[PcdValue
] = []
1611 VpdFile
.Add(Pcd
, SkuName
,Sku
.VpdOffset
)
1612 SkuValueMap
[PcdValue
].append(Sku
)
1613 # if the offset of a VPD is *, then it need to be fixed up by third party tool.
1614 if not NeedProcessVpdMapFile
and Sku
.VpdOffset
== "*":
1615 NeedProcessVpdMapFile
= True
1616 if self
.Platform
.VpdToolGuid
is None or self
.Platform
.VpdToolGuid
== '':
1617 EdkLogger
.error("Build", FILE_NOT_FOUND
, \
1618 "Fail to find third-party BPDG tool to process VPD PCDs. BPDG Guid tool need to be defined in tools_def.txt and VPD_TOOL_GUID need to be provided in DSC file.")
1620 VpdSkuMap
[PcdKey
] = SkuValueMap
1622 # Fix the PCDs define in VPD PCD section that never referenced by module.
1623 # An example is PCD for signature usage.
1625 for DscPcd
in PlatformPcds
:
1626 DscPcdEntry
= self
._PlatformPcds
[DscPcd
]
1627 if DscPcdEntry
.Type
in [TAB_PCDS_DYNAMIC_VPD
, TAB_PCDS_DYNAMIC_EX_VPD
]:
1628 if not (self
.Platform
.VpdToolGuid
is None or self
.Platform
.VpdToolGuid
== ''):
1630 for VpdPcd
in VpdFile
._VpdArray
:
1631 # This PCD has been referenced by module
1632 if (VpdPcd
.TokenSpaceGuidCName
== DscPcdEntry
.TokenSpaceGuidCName
) and \
1633 (VpdPcd
.TokenCName
== DscPcdEntry
.TokenCName
):
1636 # Not found, it should be signature
1638 # just pick the a value to determine whether is unicode string type
1640 SkuObjList
= DscPcdEntry
.SkuInfoList
.items()
1641 DefaultSku
= DscPcdEntry
.SkuInfoList
.get(TAB_DEFAULT
)
1643 defaultindex
= SkuObjList
.index((TAB_DEFAULT
,DefaultSku
))
1644 SkuObjList
[0],SkuObjList
[defaultindex
] = SkuObjList
[defaultindex
],SkuObjList
[0]
1645 for (SkuName
,Sku
) in SkuObjList
:
1646 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1648 # Need to iterate DEC pcd information to get the value & datumtype
1649 for eachDec
in self
.PackageList
:
1650 for DecPcd
in eachDec
.Pcds
:
1651 DecPcdEntry
= eachDec
.Pcds
[DecPcd
]
1652 if (DecPcdEntry
.TokenSpaceGuidCName
== DscPcdEntry
.TokenSpaceGuidCName
) and \
1653 (DecPcdEntry
.TokenCName
== DscPcdEntry
.TokenCName
):
1654 # Print warning message to let the developer make a determine.
1655 EdkLogger
.warn("build", "Unreferenced vpd pcd used!",
1656 File
=self
.MetaFile
, \
1657 ExtraData
= "PCD: %s.%s used in the DSC file %s is unreferenced." \
1658 %(DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
, self
.Platform
.MetaFile
.Path
))
1660 DscPcdEntry
.DatumType
= DecPcdEntry
.DatumType
1661 DscPcdEntry
.DefaultValue
= DecPcdEntry
.DefaultValue
1662 DscPcdEntry
.TokenValue
= DecPcdEntry
.TokenValue
1663 DscPcdEntry
.TokenSpaceGuidValue
= eachDec
.Guids
[DecPcdEntry
.TokenSpaceGuidCName
]
1664 # Only fix the value while no value provided in DSC file.
1665 if not Sku
.DefaultValue
:
1666 DscPcdEntry
.SkuInfoList
[DscPcdEntry
.SkuInfoList
.keys()[0]].DefaultValue
= DecPcdEntry
.DefaultValue
1668 if DscPcdEntry
not in self
._DynamicPcdList
:
1669 self
._DynamicPcdList
.append(DscPcdEntry
)
1670 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1671 PcdValue
= Sku
.DefaultValue
1673 PcdValue
= DscPcdEntry
.DefaultValue
1674 if Sku
.VpdOffset
!= '*':
1675 if PcdValue
.startswith("{"):
1677 elif PcdValue
.startswith("L"):
1682 VpdOffset
= int(Sku
.VpdOffset
)
1685 VpdOffset
= int(Sku
.VpdOffset
, 16)
1687 EdkLogger
.error("build", FORMAT_INVALID
, "Invalid offset value %s for PCD %s.%s." % (Sku
.VpdOffset
, DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
))
1688 if VpdOffset
% Alignment
!= 0:
1689 if PcdValue
.startswith("{"):
1690 EdkLogger
.warn("build", "The offset value of PCD %s.%s is not 8-byte aligned!" %(DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
), File
=self
.MetaFile
)
1692 EdkLogger
.error("build", FORMAT_INVALID
, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
, Alignment
))
1693 if PcdValue
not in SkuValueMap
:
1694 SkuValueMap
[PcdValue
] = []
1695 VpdFile
.Add(DscPcdEntry
, SkuName
,Sku
.VpdOffset
)
1696 SkuValueMap
[PcdValue
].append(Sku
)
1697 if not NeedProcessVpdMapFile
and Sku
.VpdOffset
== "*":
1698 NeedProcessVpdMapFile
= True
1699 if DscPcdEntry
.DatumType
== TAB_VOID
and PcdValue
.startswith("L"):
1700 UnicodePcdArray
.add(DscPcdEntry
)
1701 elif len(Sku
.VariableName
) > 0:
1702 HiiPcdArray
.add(DscPcdEntry
)
1704 OtherPcdArray
.add(DscPcdEntry
)
1706 # if the offset of a VPD is *, then it need to be fixed up by third party tool.
1707 VpdSkuMap
[DscPcd
] = SkuValueMap
1708 if (self
.Platform
.FlashDefinition
is None or self
.Platform
.FlashDefinition
== '') and \
1709 VpdFile
.GetCount() != 0:
1710 EdkLogger
.error("build", ATTRIBUTE_NOT_AVAILABLE
,
1711 "Fail to get FLASH_DEFINITION definition in DSC file %s which is required when DSC contains VPD PCD." % str(self
.Platform
.MetaFile
))
1713 if VpdFile
.GetCount() != 0:
1715 self
.FixVpdOffset(VpdFile
)
1717 self
.FixVpdOffset(self
.UpdateNVStoreMaxSize(VpdFile
))
1719 # Process VPD map file generated by third party BPDG tool
1720 if NeedProcessVpdMapFile
:
1721 VpdMapFilePath
= os
.path
.join(self
.BuildDir
, TAB_FV_DIRECTORY
, "%s.map" % self
.Platform
.VpdToolGuid
)
1722 if os
.path
.exists(VpdMapFilePath
):
1723 VpdFile
.Read(VpdMapFilePath
)
1726 for pcd
in VpdSkuMap
:
1727 vpdinfo
= VpdFile
.GetVpdInfo(pcd
)
1729 # just pick the a value to determine whether is unicode string type
1731 for pcdvalue
in VpdSkuMap
[pcd
]:
1732 for sku
in VpdSkuMap
[pcd
][pcdvalue
]:
1733 for item
in vpdinfo
:
1734 if item
[2] == pcdvalue
:
1735 sku
.VpdOffset
= item
[1]
1737 EdkLogger
.error("build", FILE_READ_FAILURE
, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath
)
1739 # Delete the DynamicPcdList At the last time enter into this function
1740 for Pcd
in self
._DynamicPcdList
:
1741 # just pick the a value to determine whether is unicode string type
1742 Sku
= Pcd
.SkuInfoList
.values()[0]
1743 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1745 if Pcd
.DatumType
not in [TAB_UINT8
, TAB_UINT16
, TAB_UINT32
, TAB_UINT64
, TAB_VOID
, "BOOLEAN"]:
1746 Pcd
.DatumType
= TAB_VOID
1748 PcdValue
= Sku
.DefaultValue
1749 if Pcd
.DatumType
== TAB_VOID
and PcdValue
.startswith("L"):
1750 # if found PCD which datum value is unicode string the insert to left size of UnicodeIndex
1751 UnicodePcdArray
.add(Pcd
)
1752 elif len(Sku
.VariableName
) > 0:
1753 # if found HII type PCD then insert to right of UnicodeIndex
1754 HiiPcdArray
.add(Pcd
)
1756 OtherPcdArray
.add(Pcd
)
1757 del self
._DynamicPcdList
[:]
1758 self
._DynamicPcdList
.extend(list(UnicodePcdArray
))
1759 self
._DynamicPcdList
.extend(list(HiiPcdArray
))
1760 self
._DynamicPcdList
.extend(list(OtherPcdArray
))
1761 allskuset
= [(SkuName
,Sku
.SkuId
) for pcd
in self
._DynamicPcdList
for (SkuName
,Sku
) in pcd
.SkuInfoList
.items()]
1762 for pcd
in self
._DynamicPcdList
:
1763 if len(pcd
.SkuInfoList
) == 1:
1764 for (SkuName
,SkuId
) in allskuset
:
1765 if type(SkuId
) in (str,unicode) and eval(SkuId
) == 0 or SkuId
== 0:
1767 pcd
.SkuInfoList
[SkuName
] = copy
.deepcopy(pcd
.SkuInfoList
[TAB_DEFAULT
])
1768 pcd
.SkuInfoList
[SkuName
].SkuId
= SkuId
1769 self
.AllPcdList
= self
._NonDynamicPcdList
+ self
._DynamicPcdList
1771 def FixVpdOffset(self
,VpdFile
):
1772 FvPath
= os
.path
.join(self
.BuildDir
, TAB_FV_DIRECTORY
)
1773 if not os
.path
.exists(FvPath
):
1777 EdkLogger
.error("build", FILE_WRITE_FAILURE
, "Fail to create FV folder under %s" % self
.BuildDir
)
1779 VpdFilePath
= os
.path
.join(FvPath
, "%s.txt" % self
.Platform
.VpdToolGuid
)
1781 if VpdFile
.Write(VpdFilePath
):
1782 # retrieve BPDG tool's path from tool_def.txt according to VPD_TOOL_GUID defined in DSC file.
1784 for ToolDef
in self
.ToolDefinition
.values():
1785 if ToolDef
.has_key(TAB_GUID
) and ToolDef
[TAB_GUID
] == self
.Platform
.VpdToolGuid
:
1786 if not ToolDef
.has_key("PATH"):
1787 EdkLogger
.error("build", ATTRIBUTE_NOT_AVAILABLE
, "PATH attribute was not provided for BPDG guid tool %s in tools_def.txt" % self
.Platform
.VpdToolGuid
)
1788 BPDGToolName
= ToolDef
["PATH"]
1790 # Call third party GUID BPDG tool.
1791 if BPDGToolName
is not None:
1792 VpdInfoFile
.CallExtenalBPDGTool(BPDGToolName
, VpdFilePath
)
1794 EdkLogger
.error("Build", FILE_NOT_FOUND
, "Fail to find third-party BPDG tool to process VPD PCDs. BPDG Guid tool need to be defined in tools_def.txt and VPD_TOOL_GUID need to be provided in DSC file.")
1796 ## Return the platform build data object
1797 def _GetPlatform(self
):
1798 if self
._Platform
is None:
1799 self
._Platform
= self
.BuildDatabase
[self
.MetaFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1800 return self
._Platform
1802 ## Return platform name
1804 return self
.Platform
.PlatformName
1806 ## Return the meta file GUID
1808 return self
.Platform
.Guid
1810 ## Return the platform version
1811 def _GetVersion(self
):
1812 return self
.Platform
.Version
1814 ## Return the FDF file name
1815 def _GetFdfFile(self
):
1816 if self
._FdfFile
is None:
1817 if self
.Workspace
.FdfFile
!= "":
1818 self
._FdfFile
= mws
.join(self
.WorkspaceDir
, self
.Workspace
.FdfFile
)
1821 return self
._FdfFile
1823 ## Return the build output directory platform specifies
1824 def _GetOutputDir(self
):
1825 return self
.Platform
.OutputDirectory
1827 ## Return the directory to store all intermediate and final files built
1828 def _GetBuildDir(self
):
1829 if self
._BuildDir
is None:
1830 if os
.path
.isabs(self
.OutputDir
):
1831 self
._BuildDir
= path
.join(
1832 path
.abspath(self
.OutputDir
),
1833 self
.BuildTarget
+ "_" + self
.ToolChain
,
1836 self
._BuildDir
= path
.join(
1839 self
.BuildTarget
+ "_" + self
.ToolChain
,
1841 GlobalData
.gBuildDirectory
= self
._BuildDir
1842 return self
._BuildDir
1844 ## Return directory of platform makefile
1846 # @retval string Makefile directory
1848 def _GetMakeFileDir(self
):
1849 if self
._MakeFileDir
is None:
1850 self
._MakeFileDir
= path
.join(self
.BuildDir
, self
.Arch
)
1851 return self
._MakeFileDir
1853 ## Return build command string
1855 # @retval string Build command string
1857 def _GetBuildCommand(self
):
1858 if self
._BuildCommand
is None:
1859 self
._BuildCommand
= []
1860 if "MAKE" in self
.ToolDefinition
and "PATH" in self
.ToolDefinition
["MAKE"]:
1861 self
._BuildCommand
+= SplitOption(self
.ToolDefinition
["MAKE"]["PATH"])
1862 if "FLAGS" in self
.ToolDefinition
["MAKE"]:
1863 NewOption
= self
.ToolDefinition
["MAKE"]["FLAGS"].strip()
1865 self
._BuildCommand
+= SplitOption(NewOption
)
1866 if "MAKE" in self
.EdkIIBuildOption
:
1867 if "FLAGS" in self
.EdkIIBuildOption
["MAKE"]:
1868 Flags
= self
.EdkIIBuildOption
["MAKE"]["FLAGS"]
1869 if Flags
.startswith('='):
1870 self
._BuildCommand
= [self
._BuildCommand
[0]] + [Flags
[1:]]
1872 self
._BuildCommand
+= [Flags
]
1873 return self
._BuildCommand
1875 ## Get tool chain definition
1877 # Get each tool defition for given tool chain from tools_def.txt and platform
1879 def _GetToolDefinition(self
):
1880 if self
._ToolDefinitions
is None:
1881 ToolDefinition
= self
.Workspace
.ToolDef
.ToolsDefTxtDictionary
1882 if TAB_TOD_DEFINES_COMMAND_TYPE
not in self
.Workspace
.ToolDef
.ToolsDefTxtDatabase
:
1883 EdkLogger
.error('build', RESOURCE_NOT_AVAILABLE
, "No tools found in configuration",
1884 ExtraData
="[%s]" % self
.MetaFile
)
1885 self
._ToolDefinitions
= {}
1887 for Def
in ToolDefinition
:
1888 Target
, Tag
, Arch
, Tool
, Attr
= Def
.split("_")
1889 if Target
!= self
.BuildTarget
or Tag
!= self
.ToolChain
or Arch
!= self
.Arch
:
1892 Value
= ToolDefinition
[Def
]
1893 # don't record the DLL
1895 DllPathList
.add(Value
)
1898 if Tool
not in self
._ToolDefinitions
:
1899 self
._ToolDefinitions
[Tool
] = {}
1900 self
._ToolDefinitions
[Tool
][Attr
] = Value
1903 if GlobalData
.gOptions
.SilentMode
and "MAKE" in self
._ToolDefinitions
:
1904 if "FLAGS" not in self
._ToolDefinitions
["MAKE"]:
1905 self
._ToolDefinitions
["MAKE"]["FLAGS"] = ""
1906 self
._ToolDefinitions
["MAKE"]["FLAGS"] += " -s"
1908 for Tool
in self
._ToolDefinitions
:
1909 for Attr
in self
._ToolDefinitions
[Tool
]:
1910 Value
= self
._ToolDefinitions
[Tool
][Attr
]
1911 if Tool
in self
.BuildOption
and Attr
in self
.BuildOption
[Tool
]:
1912 # check if override is indicated
1913 if self
.BuildOption
[Tool
][Attr
].startswith('='):
1914 Value
= self
.BuildOption
[Tool
][Attr
][1:]
1917 Value
+= " " + self
.BuildOption
[Tool
][Attr
]
1919 Value
= self
.BuildOption
[Tool
][Attr
]
1922 # Don't put MAKE definition in the file
1924 ToolsDef
+= "%s = %s\n" % (Tool
, Value
)
1926 # Don't put MAKE definition in the file
1931 ToolsDef
+= "%s_%s = %s\n" % (Tool
, Attr
, Value
)
1934 SaveFileOnChange(self
.ToolDefinitionFile
, ToolsDef
)
1935 for DllPath
in DllPathList
:
1936 os
.environ
["PATH"] = DllPath
+ os
.pathsep
+ os
.environ
["PATH"]
1937 os
.environ
["MAKE_FLAGS"] = MakeFlags
1939 return self
._ToolDefinitions
1941 ## Return the paths of tools
1942 def _GetToolDefFile(self
):
1943 if self
._ToolDefFile
is None:
1944 self
._ToolDefFile
= os
.path
.join(self
.MakeFileDir
, "TOOLS_DEF." + self
.Arch
)
1945 return self
._ToolDefFile
1947 ## Retrieve the toolchain family of given toolchain tag. Default to 'MSFT'.
1948 def _GetToolChainFamily(self
):
1949 if self
._ToolChainFamily
is None:
1950 ToolDefinition
= self
.Workspace
.ToolDef
.ToolsDefTxtDatabase
1951 if TAB_TOD_DEFINES_FAMILY
not in ToolDefinition \
1952 or self
.ToolChain
not in ToolDefinition
[TAB_TOD_DEFINES_FAMILY
] \
1953 or not ToolDefinition
[TAB_TOD_DEFINES_FAMILY
][self
.ToolChain
]:
1954 EdkLogger
.verbose("No tool chain family found in configuration for %s. Default to MSFT." \
1956 self
._ToolChainFamily
= "MSFT"
1958 self
._ToolChainFamily
= ToolDefinition
[TAB_TOD_DEFINES_FAMILY
][self
.ToolChain
]
1959 return self
._ToolChainFamily
1961 def _GetBuildRuleFamily(self
):
1962 if self
._BuildRuleFamily
is None:
1963 ToolDefinition
= self
.Workspace
.ToolDef
.ToolsDefTxtDatabase
1964 if TAB_TOD_DEFINES_BUILDRULEFAMILY
not in ToolDefinition \
1965 or self
.ToolChain
not in ToolDefinition
[TAB_TOD_DEFINES_BUILDRULEFAMILY
] \
1966 or not ToolDefinition
[TAB_TOD_DEFINES_BUILDRULEFAMILY
][self
.ToolChain
]:
1967 EdkLogger
.verbose("No tool chain family found in configuration for %s. Default to MSFT." \
1969 self
._BuildRuleFamily
= "MSFT"
1971 self
._BuildRuleFamily
= ToolDefinition
[TAB_TOD_DEFINES_BUILDRULEFAMILY
][self
.ToolChain
]
1972 return self
._BuildRuleFamily
1974 ## Return the build options specific for all modules in this platform
1975 def _GetBuildOptions(self
):
1976 if self
._BuildOption
is None:
1977 self
._BuildOption
= self
._ExpandBuildOption
(self
.Platform
.BuildOptions
)
1978 return self
._BuildOption
1980 ## Return the build options specific for EDK modules in this platform
1981 def _GetEdkBuildOptions(self
):
1982 if self
._EdkBuildOption
is None:
1983 self
._EdkBuildOption
= self
._ExpandBuildOption
(self
.Platform
.BuildOptions
, EDK_NAME
)
1984 return self
._EdkBuildOption
1986 ## Return the build options specific for EDKII modules in this platform
1987 def _GetEdkIIBuildOptions(self
):
1988 if self
._EdkIIBuildOption
is None:
1989 self
._EdkIIBuildOption
= self
._ExpandBuildOption
(self
.Platform
.BuildOptions
, EDKII_NAME
)
1990 return self
._EdkIIBuildOption
1992 ## Parse build_rule.txt in Conf Directory.
1994 # @retval BuildRule object
1996 def _GetBuildRule(self
):
1997 if self
._BuildRule
is None:
1998 BuildRuleFile
= None
1999 if TAB_TAT_DEFINES_BUILD_RULE_CONF
in self
.Workspace
.TargetTxt
.TargetTxtDictionary
:
2000 BuildRuleFile
= self
.Workspace
.TargetTxt
.TargetTxtDictionary
[TAB_TAT_DEFINES_BUILD_RULE_CONF
]
2001 if not BuildRuleFile
:
2002 BuildRuleFile
= gDefaultBuildRuleFile
2003 self
._BuildRule
= BuildRule(BuildRuleFile
)
2004 if self
._BuildRule
._FileVersion
== "":
2005 self
._BuildRule
._FileVersion
= AutoGenReqBuildRuleVerNum
2007 if self
._BuildRule
._FileVersion
< AutoGenReqBuildRuleVerNum
:
2008 # If Build Rule's version is less than the version number required by the tools, halting the build.
2009 EdkLogger
.error("build", AUTOGEN_ERROR
,
2010 ExtraData
="The version number [%s] of build_rule.txt is less than the version number required by the AutoGen.(the minimum required version number is [%s])"\
2011 % (self
._BuildRule
._FileVersion
, AutoGenReqBuildRuleVerNum
))
2013 return self
._BuildRule
2015 ## Summarize the packages used by modules in this platform
2016 def _GetPackageList(self
):
2017 if self
._PackageList
is None:
2018 self
._PackageList
= set()
2019 for La
in self
.LibraryAutoGenList
:
2020 self
._PackageList
.update(La
.DependentPackageList
)
2021 for Ma
in self
.ModuleAutoGenList
:
2022 self
._PackageList
.update(Ma
.DependentPackageList
)
2023 #Collect package set information from INF of FDF
2025 for ModuleFile
in self
._AsBuildModuleList
:
2026 if ModuleFile
in self
.Platform
.Modules
:
2028 ModuleData
= self
.BuildDatabase
[ModuleFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
2029 PkgSet
.update(ModuleData
.Packages
)
2030 self
._PackageList
= list(self
._PackageList
) + list (PkgSet
)
2031 return self
._PackageList
2033 def _GetNonDynamicPcdDict(self
):
2034 if self
._NonDynamicPcdDict
:
2035 return self
._NonDynamicPcdDict
2036 for Pcd
in self
.NonDynamicPcdList
:
2037 self
._NonDynamicPcdDict
[(Pcd
.TokenCName
,Pcd
.TokenSpaceGuidCName
)] = Pcd
2038 return self
._NonDynamicPcdDict
2040 ## Get list of non-dynamic PCDs
2041 def _GetNonDynamicPcdList(self
):
2042 if self
._NonDynamicPcdList
is None:
2043 self
.CollectPlatformDynamicPcds()
2044 return self
._NonDynamicPcdList
2046 ## Get list of dynamic PCDs
2047 def _GetDynamicPcdList(self
):
2048 if self
._DynamicPcdList
is None:
2049 self
.CollectPlatformDynamicPcds()
2050 return self
._DynamicPcdList
2052 ## Generate Token Number for all PCD
2053 def _GetPcdTokenNumbers(self
):
2054 if self
._PcdTokenNumber
is None:
2055 self
._PcdTokenNumber
= OrderedDict()
2058 # Make the Dynamic and DynamicEx PCD use within different TokenNumber area.
2062 # TokenNumber 0 ~ 10
2064 # TokeNumber 11 ~ 20
2066 for Pcd
in self
.DynamicPcdList
:
2067 if Pcd
.Phase
== "PEI":
2068 if Pcd
.Type
in PCD_DYNAMIC_TYPE_SET
:
2069 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
2070 self
._PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
2073 for Pcd
in self
.DynamicPcdList
:
2074 if Pcd
.Phase
== "PEI":
2075 if Pcd
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
2076 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
2077 self
._PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
2080 for Pcd
in self
.DynamicPcdList
:
2081 if Pcd
.Phase
== "DXE":
2082 if Pcd
.Type
in PCD_DYNAMIC_TYPE_SET
:
2083 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
2084 self
._PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
2087 for Pcd
in self
.DynamicPcdList
:
2088 if Pcd
.Phase
== "DXE":
2089 if Pcd
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
2090 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
2091 self
._PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
2094 for Pcd
in self
.NonDynamicPcdList
:
2095 self
._PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
2097 return self
._PcdTokenNumber
2099 ## Summarize ModuleAutoGen objects of all modules/libraries to be built for this platform
2100 def _GetAutoGenObjectList(self
):
2101 self
._ModuleAutoGenList
= []
2102 self
._LibraryAutoGenList
= []
2103 for ModuleFile
in self
.Platform
.Modules
:
2112 if Ma
not in self
._ModuleAutoGenList
:
2113 self
._ModuleAutoGenList
.append(Ma
)
2114 for La
in Ma
.LibraryAutoGenList
:
2115 if La
not in self
._LibraryAutoGenList
:
2116 self
._LibraryAutoGenList
.append(La
)
2117 if Ma
not in La
._ReferenceModules
:
2118 La
._ReferenceModules
.append(Ma
)
2120 ## Summarize ModuleAutoGen objects of all modules to be built for this platform
2121 def _GetModuleAutoGenList(self
):
2122 if self
._ModuleAutoGenList
is None:
2123 self
._GetAutoGenObjectList
()
2124 return self
._ModuleAutoGenList
2126 ## Summarize ModuleAutoGen objects of all libraries to be built for this platform
2127 def _GetLibraryAutoGenList(self
):
2128 if self
._LibraryAutoGenList
is None:
2129 self
._GetAutoGenObjectList
()
2130 return self
._LibraryAutoGenList
2132 ## Test if a module is supported by the platform
2134 # An error will be raised directly if the module or its arch is not supported
2135 # by the platform or current configuration
2137 def ValidModule(self
, Module
):
2138 return Module
in self
.Platform
.Modules
or Module
in self
.Platform
.LibraryInstances \
2139 or Module
in self
._AsBuildModuleList
2141 ## Resolve the library classes in a module to library instances
2143 # This method will not only resolve library classes but also sort the library
2144 # instances according to the dependency-ship.
2146 # @param Module The module from which the library classes will be resolved
2148 # @retval library_list List of library instances sorted
2150 def ApplyLibraryInstance(self
, Module
):
2151 # Cover the case that the binary INF file is list in the FDF file but not DSC file, return empty list directly
2152 if str(Module
) not in self
.Platform
.Modules
:
2155 ModuleType
= Module
.ModuleType
2157 # for overridding library instances with module specific setting
2158 PlatformModule
= self
.Platform
.Modules
[str(Module
)]
2160 # add forced library instances (specified under LibraryClasses sections)
2162 # If a module has a MODULE_TYPE of USER_DEFINED,
2163 # do not link in NULL library class instances from the global [LibraryClasses.*] sections.
2165 if Module
.ModuleType
!= SUP_MODULE_USER_DEFINED
:
2166 for LibraryClass
in self
.Platform
.LibraryClasses
.GetKeys():
2167 if LibraryClass
.startswith("NULL") and self
.Platform
.LibraryClasses
[LibraryClass
, Module
.ModuleType
]:
2168 Module
.LibraryClasses
[LibraryClass
] = self
.Platform
.LibraryClasses
[LibraryClass
, Module
.ModuleType
]
2170 # add forced library instances (specified in module overrides)
2171 for LibraryClass
in PlatformModule
.LibraryClasses
:
2172 if LibraryClass
.startswith("NULL"):
2173 Module
.LibraryClasses
[LibraryClass
] = PlatformModule
.LibraryClasses
[LibraryClass
]
2176 LibraryConsumerList
= [Module
]
2178 ConsumedByList
= OrderedDict()
2179 LibraryInstance
= OrderedDict()
2181 EdkLogger
.verbose("")
2182 EdkLogger
.verbose("Library instances of module [%s] [%s]:" % (str(Module
), self
.Arch
))
2183 while len(LibraryConsumerList
) > 0:
2184 M
= LibraryConsumerList
.pop()
2185 for LibraryClassName
in M
.LibraryClasses
:
2186 if LibraryClassName
not in LibraryInstance
:
2187 # override library instance for this module
2188 if LibraryClassName
in PlatformModule
.LibraryClasses
:
2189 LibraryPath
= PlatformModule
.LibraryClasses
[LibraryClassName
]
2191 LibraryPath
= self
.Platform
.LibraryClasses
[LibraryClassName
, ModuleType
]
2192 if LibraryPath
is None or LibraryPath
== "":
2193 LibraryPath
= M
.LibraryClasses
[LibraryClassName
]
2194 if LibraryPath
is None or LibraryPath
== "":
2195 EdkLogger
.error("build", RESOURCE_NOT_AVAILABLE
,
2196 "Instance of library class [%s] is not found" % LibraryClassName
,
2198 ExtraData
="in [%s] [%s]\n\tconsumed by module [%s]" % (str(M
), self
.Arch
, str(Module
)))
2200 LibraryModule
= self
.BuildDatabase
[LibraryPath
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
2201 # for those forced library instance (NULL library), add a fake library class
2202 if LibraryClassName
.startswith("NULL"):
2203 LibraryModule
.LibraryClass
.append(LibraryClassObject(LibraryClassName
, [ModuleType
]))
2204 elif LibraryModule
.LibraryClass
is None \
2205 or len(LibraryModule
.LibraryClass
) == 0 \
2206 or (ModuleType
!= SUP_MODULE_USER_DEFINED
2207 and ModuleType
not in LibraryModule
.LibraryClass
[0].SupModList
):
2208 # only USER_DEFINED can link against any library instance despite of its SupModList
2209 EdkLogger
.error("build", OPTION_MISSING
,
2210 "Module type [%s] is not supported by library instance [%s]" \
2211 % (ModuleType
, LibraryPath
), File
=self
.MetaFile
,
2212 ExtraData
="consumed by [%s]" % str(Module
))
2214 LibraryInstance
[LibraryClassName
] = LibraryModule
2215 LibraryConsumerList
.append(LibraryModule
)
2216 EdkLogger
.verbose("\t" + str(LibraryClassName
) + " : " + str(LibraryModule
))
2218 LibraryModule
= LibraryInstance
[LibraryClassName
]
2220 if LibraryModule
is None:
2223 if LibraryModule
.ConstructorList
!= [] and LibraryModule
not in Constructor
:
2224 Constructor
.append(LibraryModule
)
2226 if LibraryModule
not in ConsumedByList
:
2227 ConsumedByList
[LibraryModule
] = []
2228 # don't add current module itself to consumer list
2230 if M
in ConsumedByList
[LibraryModule
]:
2232 ConsumedByList
[LibraryModule
].append(M
)
2234 # Initialize the sorted output list to the empty set
2236 SortedLibraryList
= []
2238 # Q <- Set of all nodes with no incoming edges
2240 LibraryList
= [] #LibraryInstance.values()
2242 for LibraryClassName
in LibraryInstance
:
2243 M
= LibraryInstance
[LibraryClassName
]
2244 LibraryList
.append(M
)
2245 if ConsumedByList
[M
] == []:
2249 # start the DAG algorithm
2253 while Q
== [] and EdgeRemoved
:
2255 # for each node Item with a Constructor
2256 for Item
in LibraryList
:
2257 if Item
not in Constructor
:
2259 # for each Node without a constructor with an edge e from Item to Node
2260 for Node
in ConsumedByList
[Item
]:
2261 if Node
in Constructor
:
2263 # remove edge e from the graph if Node has no constructor
2264 ConsumedByList
[Item
].remove(Node
)
2266 if ConsumedByList
[Item
] == []:
2267 # insert Item into Q
2272 # DAG is done if there's no more incoming edge for all nodes
2276 # remove node from Q
2279 SortedLibraryList
.append(Node
)
2281 # for each node Item with an edge e from Node to Item do
2282 for Item
in LibraryList
:
2283 if Node
not in ConsumedByList
[Item
]:
2285 # remove edge e from the graph
2286 ConsumedByList
[Item
].remove(Node
)
2288 if ConsumedByList
[Item
] != []:
2290 # insert Item into Q, if Item has no other incoming edges
2294 # if any remaining node Item in the graph has a constructor and an incoming edge, then the graph has a cycle
2296 for Item
in LibraryList
:
2297 if ConsumedByList
[Item
] != [] and Item
in Constructor
and len(Constructor
) > 1:
2298 ErrorMessage
= "\tconsumed by " + "\n\tconsumed by ".join([str(L
) for L
in ConsumedByList
[Item
]])
2299 EdkLogger
.error("build", BUILD_ERROR
, 'Library [%s] with constructors has a cycle' % str(Item
),
2300 ExtraData
=ErrorMessage
, File
=self
.MetaFile
)
2301 if Item
not in SortedLibraryList
:
2302 SortedLibraryList
.append(Item
)
2305 # Build the list of constructor and destructir names
2306 # The DAG Topo sort produces the destructor order, so the list of constructors must generated in the reverse order
2308 SortedLibraryList
.reverse()
2309 return SortedLibraryList
2312 ## Override PCD setting (type, value, ...)
2314 # @param ToPcd The PCD to be overrided
2315 # @param FromPcd The PCD overrideing from
2317 def _OverridePcd(self
, ToPcd
, FromPcd
, Module
=""):
2319 # in case there's PCDs coming from FDF file, which have no type given.
2320 # at this point, ToPcd.Type has the type found from dependent
2323 TokenCName
= ToPcd
.TokenCName
2324 for PcdItem
in GlobalData
.MixedPcd
:
2325 if (ToPcd
.TokenCName
, ToPcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
2326 TokenCName
= PcdItem
[0]
2328 if FromPcd
is not None:
2329 if ToPcd
.Pending
and FromPcd
.Type
:
2330 ToPcd
.Type
= FromPcd
.Type
2331 elif (ToPcd
.Type
) and (FromPcd
.Type
)\
2332 and (ToPcd
.Type
!= FromPcd
.Type
) and (ToPcd
.Type
in FromPcd
.Type
):
2333 if ToPcd
.Type
.strip() == TAB_PCDS_DYNAMIC_EX
:
2334 ToPcd
.Type
= FromPcd
.Type
2335 elif ToPcd
.Type
and FromPcd
.Type \
2336 and ToPcd
.Type
!= FromPcd
.Type
:
2337 EdkLogger
.error("build", OPTION_CONFLICT
, "Mismatched PCD type",
2338 ExtraData
="%s.%s is defined as [%s] in module %s, but as [%s] in platform."\
2339 % (ToPcd
.TokenSpaceGuidCName
, TokenCName
,
2340 ToPcd
.Type
, Module
, FromPcd
.Type
),
2343 if FromPcd
.MaxDatumSize
:
2344 ToPcd
.MaxDatumSize
= FromPcd
.MaxDatumSize
2345 ToPcd
.MaxSizeUserSet
= FromPcd
.MaxDatumSize
2346 if FromPcd
.DefaultValue
:
2347 ToPcd
.DefaultValue
= FromPcd
.DefaultValue
2348 if FromPcd
.TokenValue
:
2349 ToPcd
.TokenValue
= FromPcd
.TokenValue
2350 if FromPcd
.DatumType
:
2351 ToPcd
.DatumType
= FromPcd
.DatumType
2352 if FromPcd
.SkuInfoList
:
2353 ToPcd
.SkuInfoList
= FromPcd
.SkuInfoList
2354 # Add Flexible PCD format parse
2355 if ToPcd
.DefaultValue
:
2357 ToPcd
.DefaultValue
= ValueExpressionEx(ToPcd
.DefaultValue
, ToPcd
.DatumType
, self
._GuidDict
)(True)
2358 except BadExpression
, Value
:
2359 EdkLogger
.error('Parser', FORMAT_INVALID
, 'PCD [%s.%s] Value "%s", %s' %(ToPcd
.TokenSpaceGuidCName
, ToPcd
.TokenCName
, ToPcd
.DefaultValue
, Value
),
2362 # check the validation of datum
2363 IsValid
, Cause
= CheckPcdDatum(ToPcd
.DatumType
, ToPcd
.DefaultValue
)
2365 EdkLogger
.error('build', FORMAT_INVALID
, Cause
, File
=self
.MetaFile
,
2366 ExtraData
="%s.%s" % (ToPcd
.TokenSpaceGuidCName
, TokenCName
))
2367 ToPcd
.validateranges
= FromPcd
.validateranges
2368 ToPcd
.validlists
= FromPcd
.validlists
2369 ToPcd
.expressions
= FromPcd
.expressions
2371 if FromPcd
is not None and ToPcd
.DatumType
== TAB_VOID
and not ToPcd
.MaxDatumSize
:
2372 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "No MaxDatumSize specified for PCD %s.%s" \
2373 % (ToPcd
.TokenSpaceGuidCName
, TokenCName
))
2374 Value
= ToPcd
.DefaultValue
2376 ToPcd
.MaxDatumSize
= '1'
2377 elif Value
[0] == 'L':
2378 ToPcd
.MaxDatumSize
= str((len(Value
) - 2) * 2)
2379 elif Value
[0] == '{':
2380 ToPcd
.MaxDatumSize
= str(len(Value
.split(',')))
2382 ToPcd
.MaxDatumSize
= str(len(Value
) - 1)
2384 # apply default SKU for dynamic PCDS if specified one is not available
2385 if (ToPcd
.Type
in PCD_DYNAMIC_TYPE_SET
or ToPcd
.Type
in PCD_DYNAMIC_EX_TYPE_SET
) \
2386 and not ToPcd
.SkuInfoList
:
2387 if self
.Platform
.SkuName
in self
.Platform
.SkuIds
:
2388 SkuName
= self
.Platform
.SkuName
2390 SkuName
= TAB_DEFAULT
2391 ToPcd
.SkuInfoList
= {
2392 SkuName
: SkuInfoClass(SkuName
, self
.Platform
.SkuIds
[SkuName
][0], '', '', '', '', '', ToPcd
.DefaultValue
)
2395 ## Apply PCD setting defined platform to a module
2397 # @param Module The module from which the PCD setting will be overrided
2399 # @retval PCD_list The list PCDs with settings from platform
2401 def ApplyPcdSetting(self
, Module
, Pcds
):
2402 # for each PCD in module
2403 for Name
, Guid
in Pcds
:
2404 PcdInModule
= Pcds
[Name
, Guid
]
2405 # find out the PCD setting in platform
2406 if (Name
, Guid
) in self
.Platform
.Pcds
:
2407 PcdInPlatform
= self
.Platform
.Pcds
[Name
, Guid
]
2409 PcdInPlatform
= None
2410 # then override the settings if any
2411 self
._OverridePcd
(PcdInModule
, PcdInPlatform
, Module
)
2412 # resolve the VariableGuid value
2413 for SkuId
in PcdInModule
.SkuInfoList
:
2414 Sku
= PcdInModule
.SkuInfoList
[SkuId
]
2415 if Sku
.VariableGuid
== '': continue
2416 Sku
.VariableGuidValue
= GuidValue(Sku
.VariableGuid
, self
.PackageList
, self
.MetaFile
.Path
)
2417 if Sku
.VariableGuidValue
is None:
2418 PackageList
= "\n\t".join([str(P
) for P
in self
.PackageList
])
2421 RESOURCE_NOT_AVAILABLE
,
2422 "Value of GUID [%s] is not found in" % Sku
.VariableGuid
,
2423 ExtraData
=PackageList
+ "\n\t(used with %s.%s from module %s)" \
2424 % (Guid
, Name
, str(Module
)),
2428 # override PCD settings with module specific setting
2429 if Module
in self
.Platform
.Modules
:
2430 PlatformModule
= self
.Platform
.Modules
[str(Module
)]
2431 for Key
in PlatformModule
.Pcds
:
2436 elif Key
in GlobalData
.MixedPcd
:
2437 for PcdItem
in GlobalData
.MixedPcd
[Key
]:
2439 ToPcd
= Pcds
[PcdItem
]
2443 self
._OverridePcd
(ToPcd
, PlatformModule
.Pcds
[Key
], Module
)
2444 # use PCD value to calculate the MaxDatumSize when it is not specified
2445 for Name
, Guid
in Pcds
:
2446 Pcd
= Pcds
[Name
, Guid
]
2447 if Pcd
.DatumType
== TAB_VOID
and not Pcd
.MaxDatumSize
:
2448 Pcd
.MaxSizeUserSet
= None
2449 Value
= Pcd
.DefaultValue
2451 Pcd
.MaxDatumSize
= '1'
2452 elif Value
[0] == 'L':
2453 Pcd
.MaxDatumSize
= str((len(Value
) - 2) * 2)
2454 elif Value
[0] == '{':
2455 Pcd
.MaxDatumSize
= str(len(Value
.split(',')))
2457 Pcd
.MaxDatumSize
= str(len(Value
) - 1)
2458 return Pcds
.values()
2460 ## Resolve library names to library modules
2462 # (for Edk.x modules)
2464 # @param Module The module from which the library names will be resolved
2466 # @retval library_list The list of library modules
2468 def ResolveLibraryReference(self
, Module
):
2469 EdkLogger
.verbose("")
2470 EdkLogger
.verbose("Library instances of module [%s] [%s]:" % (str(Module
), self
.Arch
))
2471 LibraryConsumerList
= [Module
]
2473 # "CompilerStub" is a must for Edk modules
2474 if Module
.Libraries
:
2475 Module
.Libraries
.append("CompilerStub")
2477 while len(LibraryConsumerList
) > 0:
2478 M
= LibraryConsumerList
.pop()
2479 for LibraryName
in M
.Libraries
:
2480 Library
= self
.Platform
.LibraryClasses
[LibraryName
, ':dummy:']
2482 for Key
in self
.Platform
.LibraryClasses
.data
:
2483 if LibraryName
.upper() == Key
.upper():
2484 Library
= self
.Platform
.LibraryClasses
[Key
, ':dummy:']
2487 EdkLogger
.warn("build", "Library [%s] is not found" % LibraryName
, File
=str(M
),
2488 ExtraData
="\t%s [%s]" % (str(Module
), self
.Arch
))
2491 if Library
not in LibraryList
:
2492 LibraryList
.append(Library
)
2493 LibraryConsumerList
.append(Library
)
2494 EdkLogger
.verbose("\t" + LibraryName
+ " : " + str(Library
) + ' ' + str(type(Library
)))
2497 ## Calculate the priority value of the build option
2499 # @param Key Build option definition contain: TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
2501 # @retval Value Priority value based on the priority list.
2503 def CalculatePriorityValue(self
, Key
):
2504 Target
, ToolChain
, Arch
, CommandType
, Attr
= Key
.split('_')
2505 PriorityValue
= 0x11111
2507 PriorityValue
&= 0x01111
2508 if ToolChain
== "*":
2509 PriorityValue
&= 0x10111
2511 PriorityValue
&= 0x11011
2512 if CommandType
== "*":
2513 PriorityValue
&= 0x11101
2515 PriorityValue
&= 0x11110
2517 return self
.PrioList
["0x%0.5x" % PriorityValue
]
2520 ## Expand * in build option key
2522 # @param Options Options to be expanded
2524 # @retval options Options expanded
2526 def _ExpandBuildOption(self
, Options
, ModuleStyle
=None):
2533 # Construct a list contain the build options which need override.
2537 # Key[0] -- tool family
2538 # Key[1] -- TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
2540 if (Key
[0] == self
.BuildRuleFamily
and
2541 (ModuleStyle
is None or len(Key
) < 3 or (len(Key
) > 2 and Key
[2] == ModuleStyle
))):
2542 Target
, ToolChain
, Arch
, CommandType
, Attr
= Key
[1].split('_')
2543 if Target
== self
.BuildTarget
or Target
== "*":
2544 if ToolChain
== self
.ToolChain
or ToolChain
== "*":
2545 if Arch
== self
.Arch
or Arch
== "*":
2546 if Options
[Key
].startswith("="):
2547 if OverrideList
.get(Key
[1]) is not None:
2548 OverrideList
.pop(Key
[1])
2549 OverrideList
[Key
[1]] = Options
[Key
]
2552 # Use the highest priority value.
2554 if (len(OverrideList
) >= 2):
2555 KeyList
= OverrideList
.keys()
2556 for Index
in range(len(KeyList
)):
2557 NowKey
= KeyList
[Index
]
2558 Target1
, ToolChain1
, Arch1
, CommandType1
, Attr1
= NowKey
.split("_")
2559 for Index1
in range(len(KeyList
) - Index
- 1):
2560 NextKey
= KeyList
[Index1
+ Index
+ 1]
2562 # Compare two Key, if one is included by another, choose the higher priority one
2564 Target2
, ToolChain2
, Arch2
, CommandType2
, Attr2
= NextKey
.split("_")
2565 if Target1
== Target2
or Target1
== "*" or Target2
== "*":
2566 if ToolChain1
== ToolChain2
or ToolChain1
== "*" or ToolChain2
== "*":
2567 if Arch1
== Arch2
or Arch1
== "*" or Arch2
== "*":
2568 if CommandType1
== CommandType2
or CommandType1
== "*" or CommandType2
== "*":
2569 if Attr1
== Attr2
or Attr1
== "*" or Attr2
== "*":
2570 if self
.CalculatePriorityValue(NowKey
) > self
.CalculatePriorityValue(NextKey
):
2571 if Options
.get((self
.BuildRuleFamily
, NextKey
)) is not None:
2572 Options
.pop((self
.BuildRuleFamily
, NextKey
))
2574 if Options
.get((self
.BuildRuleFamily
, NowKey
)) is not None:
2575 Options
.pop((self
.BuildRuleFamily
, NowKey
))
2578 if ModuleStyle
is not None and len (Key
) > 2:
2579 # Check Module style is EDK or EDKII.
2580 # Only append build option for the matched style module.
2581 if ModuleStyle
== EDK_NAME
and Key
[2] != EDK_NAME
:
2583 elif ModuleStyle
== EDKII_NAME
and Key
[2] != EDKII_NAME
:
2586 Target
, Tag
, Arch
, Tool
, Attr
= Key
[1].split("_")
2587 # if tool chain family doesn't match, skip it
2588 if Tool
in self
.ToolDefinition
and Family
!= "":
2589 FamilyIsNull
= False
2590 if self
.ToolDefinition
[Tool
].get(TAB_TOD_DEFINES_BUILDRULEFAMILY
, "") != "":
2591 if Family
!= self
.ToolDefinition
[Tool
][TAB_TOD_DEFINES_BUILDRULEFAMILY
]:
2593 elif Family
!= self
.ToolDefinition
[Tool
][TAB_TOD_DEFINES_FAMILY
]:
2596 # expand any wildcard
2597 if Target
== "*" or Target
== self
.BuildTarget
:
2598 if Tag
== "*" or Tag
== self
.ToolChain
:
2599 if Arch
== "*" or Arch
== self
.Arch
:
2600 if Tool
not in BuildOptions
:
2601 BuildOptions
[Tool
] = {}
2602 if Attr
!= "FLAGS" or Attr
not in BuildOptions
[Tool
] or Options
[Key
].startswith('='):
2603 BuildOptions
[Tool
][Attr
] = Options
[Key
]
2605 # append options for the same tool except PATH
2607 BuildOptions
[Tool
][Attr
] += " " + Options
[Key
]
2609 BuildOptions
[Tool
][Attr
] = Options
[Key
]
2610 # Build Option Family has been checked, which need't to be checked again for family.
2611 if FamilyMatch
or FamilyIsNull
:
2615 if ModuleStyle
is not None and len (Key
) > 2:
2616 # Check Module style is EDK or EDKII.
2617 # Only append build option for the matched style module.
2618 if ModuleStyle
== EDK_NAME
and Key
[2] != EDK_NAME
:
2620 elif ModuleStyle
== EDKII_NAME
and Key
[2] != EDKII_NAME
:
2623 Target
, Tag
, Arch
, Tool
, Attr
= Key
[1].split("_")
2624 # if tool chain family doesn't match, skip it
2625 if Tool
not in self
.ToolDefinition
or Family
== "":
2627 # option has been added before
2628 if Family
!= self
.ToolDefinition
[Tool
][TAB_TOD_DEFINES_FAMILY
]:
2631 # expand any wildcard
2632 if Target
== "*" or Target
== self
.BuildTarget
:
2633 if Tag
== "*" or Tag
== self
.ToolChain
:
2634 if Arch
== "*" or Arch
== self
.Arch
:
2635 if Tool
not in BuildOptions
:
2636 BuildOptions
[Tool
] = {}
2637 if Attr
!= "FLAGS" or Attr
not in BuildOptions
[Tool
] or Options
[Key
].startswith('='):
2638 BuildOptions
[Tool
][Attr
] = Options
[Key
]
2640 # append options for the same tool except PATH
2642 BuildOptions
[Tool
][Attr
] += " " + Options
[Key
]
2644 BuildOptions
[Tool
][Attr
] = Options
[Key
]
2647 ## Append build options in platform to a module
2649 # @param Module The module to which the build options will be appened
2651 # @retval options The options appended with build options in platform
2653 def ApplyBuildOption(self
, Module
):
2654 # Get the different options for the different style module
2655 if Module
.AutoGenVersion
< 0x00010005:
2656 PlatformOptions
= self
.EdkBuildOption
2657 ModuleTypeOptions
= self
.Platform
.GetBuildOptionsByModuleType(EDK_NAME
, Module
.ModuleType
)
2659 PlatformOptions
= self
.EdkIIBuildOption
2660 ModuleTypeOptions
= self
.Platform
.GetBuildOptionsByModuleType(EDKII_NAME
, Module
.ModuleType
)
2661 ModuleTypeOptions
= self
._ExpandBuildOption
(ModuleTypeOptions
)
2662 ModuleOptions
= self
._ExpandBuildOption
(Module
.BuildOptions
)
2663 if Module
in self
.Platform
.Modules
:
2664 PlatformModule
= self
.Platform
.Modules
[str(Module
)]
2665 PlatformModuleOptions
= self
._ExpandBuildOption
(PlatformModule
.BuildOptions
)
2667 PlatformModuleOptions
= {}
2669 BuildRuleOrder
= None
2670 for Options
in [self
.ToolDefinition
, ModuleOptions
, PlatformOptions
, ModuleTypeOptions
, PlatformModuleOptions
]:
2671 for Tool
in Options
:
2672 for Attr
in Options
[Tool
]:
2673 if Attr
== TAB_TOD_DEFINES_BUILDRULEORDER
:
2674 BuildRuleOrder
= Options
[Tool
][Attr
]
2676 AllTools
= set(ModuleOptions
.keys() + PlatformOptions
.keys() +
2677 PlatformModuleOptions
.keys() + ModuleTypeOptions
.keys() +
2678 self
.ToolDefinition
.keys())
2679 BuildOptions
= defaultdict(lambda: defaultdict(str))
2680 for Tool
in AllTools
:
2681 for Options
in [self
.ToolDefinition
, ModuleOptions
, PlatformOptions
, ModuleTypeOptions
, PlatformModuleOptions
]:
2682 if Tool
not in Options
:
2684 for Attr
in Options
[Tool
]:
2686 # Do not generate it in Makefile
2688 if Attr
== TAB_TOD_DEFINES_BUILDRULEORDER
:
2690 Value
= Options
[Tool
][Attr
]
2691 # check if override is indicated
2692 if Value
.startswith('='):
2693 BuildOptions
[Tool
][Attr
] = mws
.handleWsMacro(Value
[1:])
2696 BuildOptions
[Tool
][Attr
] += " " + mws
.handleWsMacro(Value
)
2698 BuildOptions
[Tool
][Attr
] = mws
.handleWsMacro(Value
)
2700 if Module
.AutoGenVersion
< 0x00010005 and self
.Workspace
.UniFlag
is not None:
2702 # Override UNI flag only for EDK module.
2704 BuildOptions
['BUILD']['FLAGS'] = self
.Workspace
.UniFlag
2705 return BuildOptions
, BuildRuleOrder
2707 Platform
= property(_GetPlatform
)
2708 Name
= property(_GetName
)
2709 Guid
= property(_GetGuid
)
2710 Version
= property(_GetVersion
)
2712 OutputDir
= property(_GetOutputDir
)
2713 BuildDir
= property(_GetBuildDir
)
2714 MakeFileDir
= property(_GetMakeFileDir
)
2715 FdfFile
= property(_GetFdfFile
)
2717 PcdTokenNumber
= property(_GetPcdTokenNumbers
) # (TokenCName, TokenSpaceGuidCName) : GeneratedTokenNumber
2718 DynamicPcdList
= property(_GetDynamicPcdList
) # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
2719 NonDynamicPcdList
= property(_GetNonDynamicPcdList
) # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
2720 NonDynamicPcdDict
= property(_GetNonDynamicPcdDict
)
2721 PackageList
= property(_GetPackageList
)
2723 ToolDefinition
= property(_GetToolDefinition
) # toolcode : tool path
2724 ToolDefinitionFile
= property(_GetToolDefFile
) # toolcode : lib path
2725 ToolChainFamily
= property(_GetToolChainFamily
)
2726 BuildRuleFamily
= property(_GetBuildRuleFamily
)
2727 BuildOption
= property(_GetBuildOptions
) # toolcode : option
2728 EdkBuildOption
= property(_GetEdkBuildOptions
) # edktoolcode : option
2729 EdkIIBuildOption
= property(_GetEdkIIBuildOptions
) # edkiitoolcode : option
2731 BuildCommand
= property(_GetBuildCommand
)
2732 BuildRule
= property(_GetBuildRule
)
2733 ModuleAutoGenList
= property(_GetModuleAutoGenList
)
2734 LibraryAutoGenList
= property(_GetLibraryAutoGenList
)
2735 GenFdsCommand
= property(_GenFdsCommand
)
2737 ## ModuleAutoGen class
2739 # This class encapsules the AutoGen behaviors for the build tools. In addition to
2740 # the generation of AutoGen.h and AutoGen.c, it will generate *.depex file according
2741 # to the [depex] section in module's inf file.
2743 class ModuleAutoGen(AutoGen
):
2744 # call super().__init__ then call the worker function with different parameter count
2745 def __init__(self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
2749 super(ModuleAutoGen
, self
).__init
__(Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
)
2750 self
._InitWorker
(Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
)
2753 ## Cache the timestamps of metafiles of every module in a class variable
2757 def __new__(cls
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
2758 obj
= super(ModuleAutoGen
, cls
).__new
__(cls
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
)
2759 # check if this module is employed by active platform
2760 if not PlatformAutoGen(Workspace
, args
[0], Target
, Toolchain
, Arch
).ValidModule(MetaFile
):
2761 EdkLogger
.verbose("Module [%s] for [%s] is not employed by active platform\n" \
2766 ## Initialize ModuleAutoGen
2768 # @param Workspace EdkIIWorkspaceBuild object
2769 # @param ModuleFile The path of module file
2770 # @param Target Build target (DEBUG, RELEASE)
2771 # @param Toolchain Name of tool chain
2772 # @param Arch The arch the module supports
2773 # @param PlatformFile Platform meta-file
2775 def _InitWorker(self
, Workspace
, ModuleFile
, Target
, Toolchain
, Arch
, PlatformFile
):
2776 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "AutoGen module [%s] [%s]" % (ModuleFile
, Arch
))
2777 GlobalData
.gProcessingFile
= "%s [%s, %s, %s]" % (ModuleFile
, Arch
, Toolchain
, Target
)
2779 self
.Workspace
= Workspace
2780 self
.WorkspaceDir
= Workspace
.WorkspaceDir
2781 self
._GuidDict
= Workspace
._GuidDict
2782 self
.MetaFile
= ModuleFile
2783 self
.PlatformInfo
= PlatformAutoGen(Workspace
, PlatformFile
, Target
, Toolchain
, Arch
)
2785 self
.SourceDir
= self
.MetaFile
.SubDir
2786 self
.SourceDir
= mws
.relpath(self
.SourceDir
, self
.WorkspaceDir
)
2788 self
.SourceOverrideDir
= None
2789 # use overrided path defined in DSC file
2790 if self
.MetaFile
.Key
in GlobalData
.gOverrideDir
:
2791 self
.SourceOverrideDir
= GlobalData
.gOverrideDir
[self
.MetaFile
.Key
]
2793 self
.ToolChain
= Toolchain
2794 self
.BuildTarget
= Target
2796 self
.ToolChainFamily
= self
.PlatformInfo
.ToolChainFamily
2797 self
.BuildRuleFamily
= self
.PlatformInfo
.BuildRuleFamily
2799 self
.IsMakeFileCreated
= False
2800 self
.IsCodeFileCreated
= False
2801 self
.IsAsBuiltInfCreated
= False
2802 self
.DepexGenerated
= False
2804 self
.BuildDatabase
= self
.Workspace
.BuildDatabase
2805 self
.BuildRuleOrder
= None
2811 self
._Version
= None
2812 self
._ModuleType
= None
2813 self
._ComponentType
= None
2814 self
._PcdIsDriver
= None
2815 self
._AutoGenVersion
= None
2816 self
._LibraryFlag
= None
2817 self
._CustomMakefile
= None
2820 self
._BuildDir
= None
2821 self
._OutputDir
= None
2822 self
._FfsOutputDir
= None
2823 self
._DebugDir
= None
2824 self
._MakeFileDir
= None
2826 self
._IncludePathList
= None
2827 self
._IncludePathLength
= 0
2828 self
._AutoGenFileList
= None
2829 self
._UnicodeFileList
= None
2830 self
._VfrFileList
= None
2831 self
._IdfFileList
= None
2832 self
._SourceFileList
= None
2833 self
._ObjectFileList
= None
2834 self
._BinaryFileList
= None
2836 self
._DependentPackageList
= None
2837 self
._DependentLibraryList
= None
2838 self
._LibraryAutoGenList
= None
2839 self
._DerivedPackageList
= None
2840 self
._ModulePcdList
= None
2841 self
._LibraryPcdList
= None
2842 self
._PcdComments
= OrderedDict()
2843 self
._GuidList
= None
2844 self
._GuidsUsedByPcd
= None
2845 self
._GuidComments
= OrderedDict()
2846 self
._ProtocolList
= None
2847 self
._ProtocolComments
= OrderedDict()
2848 self
._PpiList
= None
2849 self
._PpiComments
= OrderedDict()
2850 self
._DepexList
= None
2851 self
._DepexExpressionList
= None
2852 self
._BuildOption
= None
2853 self
._BuildOptionIncPathList
= None
2854 self
._BuildTargets
= None
2855 self
._IntroBuildTargetList
= None
2856 self
._FinalBuildTargetList
= None
2857 self
._FileTypes
= None
2858 self
._BuildRules
= None
2860 self
._TimeStampPath
= None
2862 self
.AutoGenDepSet
= set()
2865 ## The Modules referenced to this Library
2866 # Only Library has this attribute
2867 self
._ReferenceModules
= []
2869 ## Store the FixedAtBuild Pcds
2871 self
._FixedAtBuildPcds
= []
2876 return "%s [%s]" % (self
.MetaFile
, self
.Arch
)
2878 # Get FixedAtBuild Pcds of this Module
2879 def _GetFixedAtBuildPcds(self
):
2880 if self
._FixedAtBuildPcds
:
2881 return self
._FixedAtBuildPcds
2882 for Pcd
in self
.ModulePcdList
:
2883 if Pcd
.Type
!= TAB_PCDS_FIXED_AT_BUILD
:
2885 if Pcd
not in self
._FixedAtBuildPcds
:
2886 self
._FixedAtBuildPcds
.append(Pcd
)
2888 return self
._FixedAtBuildPcds
2890 def _GetUniqueBaseName(self
):
2891 BaseName
= self
.Name
2892 for Module
in self
.PlatformInfo
.ModuleAutoGenList
:
2893 if Module
.MetaFile
== self
.MetaFile
:
2895 if Module
.Name
== self
.Name
:
2896 if uuid
.UUID(Module
.Guid
) == uuid
.UUID(self
.Guid
):
2897 EdkLogger
.error("build", FILE_DUPLICATED
, 'Modules have same BaseName and FILE_GUID:\n'
2898 ' %s\n %s' % (Module
.MetaFile
, self
.MetaFile
))
2899 BaseName
= '%s_%s' % (self
.Name
, self
.Guid
)
2902 # Macros could be used in build_rule.txt (also Makefile)
2903 def _GetMacros(self
):
2904 if self
._Macro
is None:
2905 self
._Macro
= OrderedDict()
2906 self
._Macro
["WORKSPACE" ] = self
.WorkspaceDir
2907 self
._Macro
["MODULE_NAME" ] = self
.Name
2908 self
._Macro
["MODULE_NAME_GUID" ] = self
._GetUniqueBaseName
()
2909 self
._Macro
["MODULE_GUID" ] = self
.Guid
2910 self
._Macro
["MODULE_VERSION" ] = self
.Version
2911 self
._Macro
["MODULE_TYPE" ] = self
.ModuleType
2912 self
._Macro
["MODULE_FILE" ] = str(self
.MetaFile
)
2913 self
._Macro
["MODULE_FILE_BASE_NAME" ] = self
.MetaFile
.BaseName
2914 self
._Macro
["MODULE_RELATIVE_DIR" ] = self
.SourceDir
2915 self
._Macro
["MODULE_DIR" ] = self
.SourceDir
2917 self
._Macro
["BASE_NAME" ] = self
.Name
2919 self
._Macro
["ARCH" ] = self
.Arch
2920 self
._Macro
["TOOLCHAIN" ] = self
.ToolChain
2921 self
._Macro
["TOOLCHAIN_TAG" ] = self
.ToolChain
2922 self
._Macro
["TOOL_CHAIN_TAG" ] = self
.ToolChain
2923 self
._Macro
["TARGET" ] = self
.BuildTarget
2925 self
._Macro
["BUILD_DIR" ] = self
.PlatformInfo
.BuildDir
2926 self
._Macro
["BIN_DIR" ] = os
.path
.join(self
.PlatformInfo
.BuildDir
, self
.Arch
)
2927 self
._Macro
["LIB_DIR" ] = os
.path
.join(self
.PlatformInfo
.BuildDir
, self
.Arch
)
2928 self
._Macro
["MODULE_BUILD_DIR" ] = self
.BuildDir
2929 self
._Macro
["OUTPUT_DIR" ] = self
.OutputDir
2930 self
._Macro
["DEBUG_DIR" ] = self
.DebugDir
2931 self
._Macro
["DEST_DIR_OUTPUT" ] = self
.OutputDir
2932 self
._Macro
["DEST_DIR_DEBUG" ] = self
.DebugDir
2933 self
._Macro
["PLATFORM_NAME" ] = self
.PlatformInfo
.Name
2934 self
._Macro
["PLATFORM_GUID" ] = self
.PlatformInfo
.Guid
2935 self
._Macro
["PLATFORM_VERSION" ] = self
.PlatformInfo
.Version
2936 self
._Macro
["PLATFORM_RELATIVE_DIR" ] = self
.PlatformInfo
.SourceDir
2937 self
._Macro
["PLATFORM_DIR" ] = mws
.join(self
.WorkspaceDir
, self
.PlatformInfo
.SourceDir
)
2938 self
._Macro
["PLATFORM_OUTPUT_DIR" ] = self
.PlatformInfo
.OutputDir
2939 self
._Macro
["FFS_OUTPUT_DIR" ] = self
.FfsOutputDir
2942 ## Return the module build data object
2943 def _GetModule(self
):
2944 if self
._Module
is None:
2945 self
._Module
= self
.Workspace
.BuildDatabase
[self
.MetaFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
2948 ## Return the module name
2949 def _GetBaseName(self
):
2950 return self
.Module
.BaseName
2952 ## Return the module DxsFile if exist
2953 def _GetDxsFile(self
):
2954 return self
.Module
.DxsFile
2956 ## Return the module SourceOverridePath
2957 def _GetSourceOverridePath(self
):
2958 return self
.Module
.SourceOverridePath
2960 ## Return the module meta-file GUID
2963 # To build same module more than once, the module path with FILE_GUID overridden has
2964 # the file name FILE_GUIDmodule.inf, but the relative path (self.MetaFile.File) is the realy path
2965 # in DSC. The overridden GUID can be retrieved from file name
2967 if os
.path
.basename(self
.MetaFile
.File
) != os
.path
.basename(self
.MetaFile
.Path
):
2969 # Length of GUID is 36
2971 return os
.path
.basename(self
.MetaFile
.Path
)[:36]
2972 return self
.Module
.Guid
2974 ## Return the module version
2975 def _GetVersion(self
):
2976 return self
.Module
.Version
2978 ## Return the module type
2979 def _GetModuleType(self
):
2980 return self
.Module
.ModuleType
2982 ## Return the component type (for Edk.x style of module)
2983 def _GetComponentType(self
):
2984 return self
.Module
.ComponentType
2986 ## Return the build type
2987 def _GetBuildType(self
):
2988 return self
.Module
.BuildType
2990 ## Return the PCD_IS_DRIVER setting
2991 def _GetPcdIsDriver(self
):
2992 return self
.Module
.PcdIsDriver
2994 ## Return the autogen version, i.e. module meta-file version
2995 def _GetAutoGenVersion(self
):
2996 return self
.Module
.AutoGenVersion
2998 ## Check if the module is library or not
2999 def _IsLibrary(self
):
3000 if self
._LibraryFlag
is None:
3001 if self
.Module
.LibraryClass
is not None and self
.Module
.LibraryClass
!= []:
3002 self
._LibraryFlag
= True
3004 self
._LibraryFlag
= False
3005 return self
._LibraryFlag
3007 ## Check if the module is binary module or not
3008 def _IsBinaryModule(self
):
3009 return self
.Module
.IsBinaryModule
3011 ## Return the directory to store intermediate files of the module
3012 def _GetBuildDir(self
):
3013 if self
._BuildDir
is None:
3014 self
._BuildDir
= path
.join(
3015 self
.PlatformInfo
.BuildDir
,
3018 self
.MetaFile
.BaseName
3020 CreateDirectory(self
._BuildDir
)
3021 return self
._BuildDir
3023 ## Return the directory to store the intermediate object files of the mdoule
3024 def _GetOutputDir(self
):
3025 if self
._OutputDir
is None:
3026 self
._OutputDir
= path
.join(self
.BuildDir
, "OUTPUT")
3027 CreateDirectory(self
._OutputDir
)
3028 return self
._OutputDir
3030 ## Return the directory to store ffs file
3031 def _GetFfsOutputDir(self
):
3032 if self
._FfsOutputDir
is None:
3033 if GlobalData
.gFdfParser
is not None:
3034 self
._FfsOutputDir
= path
.join(self
.PlatformInfo
.BuildDir
, TAB_FV_DIRECTORY
, "Ffs", self
.Guid
+ self
.Name
)
3036 self
._FfsOutputDir
= ''
3037 return self
._FfsOutputDir
3039 ## Return the directory to store auto-gened source files of the mdoule
3040 def _GetDebugDir(self
):
3041 if self
._DebugDir
is None:
3042 self
._DebugDir
= path
.join(self
.BuildDir
, "DEBUG")
3043 CreateDirectory(self
._DebugDir
)
3044 return self
._DebugDir
3046 ## Return the path of custom file
3047 def _GetCustomMakefile(self
):
3048 if self
._CustomMakefile
is None:
3049 self
._CustomMakefile
= {}
3050 for Type
in self
.Module
.CustomMakefile
:
3051 if Type
in gMakeTypeMap
:
3052 MakeType
= gMakeTypeMap
[Type
]
3055 if self
.SourceOverrideDir
is not None:
3056 File
= os
.path
.join(self
.SourceOverrideDir
, self
.Module
.CustomMakefile
[Type
])
3057 if not os
.path
.exists(File
):
3058 File
= os
.path
.join(self
.SourceDir
, self
.Module
.CustomMakefile
[Type
])
3060 File
= os
.path
.join(self
.SourceDir
, self
.Module
.CustomMakefile
[Type
])
3061 self
._CustomMakefile
[MakeType
] = File
3062 return self
._CustomMakefile
3064 ## Return the directory of the makefile
3066 # @retval string The directory string of module's makefile
3068 def _GetMakeFileDir(self
):
3069 return self
.BuildDir
3071 ## Return build command string
3073 # @retval string Build command string
3075 def _GetBuildCommand(self
):
3076 return self
.PlatformInfo
.BuildCommand
3078 ## Get object list of all packages the module and its dependent libraries belong to
3080 # @retval list The list of package object
3082 def _GetDerivedPackageList(self
):
3084 for M
in [self
.Module
] + self
.DependentLibraryList
:
3085 for Package
in M
.Packages
:
3086 if Package
in PackageList
:
3088 PackageList
.append(Package
)
3091 ## Get the depex string
3093 # @return : a string contain all depex expresion.
3094 def _GetDepexExpresionString(self
):
3097 ## DPX_SOURCE IN Define section.
3098 if self
.Module
.DxsFile
:
3100 for M
in [self
.Module
] + self
.DependentLibraryList
:
3101 Filename
= M
.MetaFile
.Path
3102 InfObj
= InfSectionParser
.InfSectionParser(Filename
)
3103 DepexExpresionList
= InfObj
.GetDepexExpresionList()
3104 for DepexExpresion
in DepexExpresionList
:
3105 for key
in DepexExpresion
:
3106 Arch
, ModuleType
= key
3107 DepexExpr
= [x
for x
in DepexExpresion
[key
] if not str(x
).startswith('#')]
3108 # the type of build module is USER_DEFINED.
3109 # All different DEPEX section tags would be copied into the As Built INF file
3110 # and there would be separate DEPEX section tags
3111 if self
.ModuleType
.upper() == SUP_MODULE_USER_DEFINED
:
3112 if (Arch
.upper() == self
.Arch
.upper()) and (ModuleType
.upper() != TAB_ARCH_COMMON
):
3113 DepexList
.append({(Arch
, ModuleType
): DepexExpr
})
3115 if Arch
.upper() == TAB_ARCH_COMMON
or \
3116 (Arch
.upper() == self
.Arch
.upper() and \
3117 ModuleType
.upper() in [TAB_ARCH_COMMON
, self
.ModuleType
.upper()]):
3118 DepexList
.append({(Arch
, ModuleType
): DepexExpr
})
3120 #the type of build module is USER_DEFINED.
3121 if self
.ModuleType
.upper() == SUP_MODULE_USER_DEFINED
:
3122 for Depex
in DepexList
:
3124 DepexStr
+= '[Depex.%s.%s]\n' % key
3125 DepexStr
+= '\n'.join(['# '+ val
for val
in Depex
[key
]])
3128 return '[Depex.%s]\n' % self
.Arch
3131 #the type of build module not is USER_DEFINED.
3133 for Depex
in DepexList
:
3138 for D
in Depex
.values():
3139 DepexStr
+= ' '.join([val
for val
in D
])
3140 Index
= DepexStr
.find('END')
3141 if Index
> -1 and Index
== len(DepexStr
) - 3:
3142 DepexStr
= DepexStr
[:-3]
3143 DepexStr
= DepexStr
.strip()
3146 DepexStr
= DepexStr
.lstrip('(').rstrip(')').strip()
3148 return '[Depex.%s]\n' % self
.Arch
3149 return '[Depex.%s]\n# ' % self
.Arch
+ DepexStr
3151 ## Merge dependency expression
3153 # @retval list The token list of the dependency expression after parsed
3155 def _GetDepexTokenList(self
):
3156 if self
._DepexList
is None:
3157 self
._DepexList
= {}
3158 if self
.DxsFile
or self
.IsLibrary
or TAB_DEPENDENCY_EXPRESSION_FILE
in self
.FileTypes
:
3159 return self
._DepexList
3161 self
._DepexList
[self
.ModuleType
] = []
3163 for ModuleType
in self
._DepexList
:
3164 DepexList
= self
._DepexList
[ModuleType
]
3166 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion
3168 for M
in [self
.Module
] + self
.DependentLibraryList
:
3170 for D
in M
.Depex
[self
.Arch
, ModuleType
]:
3172 DepexList
.append('AND')
3173 DepexList
.append('(')
3175 if DepexList
[-1] == 'END': # no need of a END at this time
3177 DepexList
.append(')')
3180 EdkLogger
.verbose("DEPEX[%s] (+%s) = %s" % (self
.Name
, M
.BaseName
, DepexList
))
3181 if 'BEFORE' in DepexList
or 'AFTER' in DepexList
:
3183 if len(DepexList
) > 0:
3184 EdkLogger
.verbose('')
3185 return self
._DepexList
3187 ## Merge dependency expression
3189 # @retval list The token list of the dependency expression after parsed
3191 def _GetDepexExpressionTokenList(self
):
3192 if self
._DepexExpressionList
is None:
3193 self
._DepexExpressionList
= {}
3194 if self
.DxsFile
or self
.IsLibrary
or TAB_DEPENDENCY_EXPRESSION_FILE
in self
.FileTypes
:
3195 return self
._DepexExpressionList
3197 self
._DepexExpressionList
[self
.ModuleType
] = ''
3199 for ModuleType
in self
._DepexExpressionList
:
3200 DepexExpressionList
= self
._DepexExpressionList
[ModuleType
]
3202 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion
3204 for M
in [self
.Module
] + self
.DependentLibraryList
:
3206 for D
in M
.DepexExpression
[self
.Arch
, ModuleType
]:
3207 if DepexExpressionList
!= '':
3208 DepexExpressionList
+= ' AND '
3209 DepexExpressionList
+= '('
3210 DepexExpressionList
+= D
3211 DepexExpressionList
= DepexExpressionList
.rstrip('END').strip()
3212 DepexExpressionList
+= ')'
3215 EdkLogger
.verbose("DEPEX[%s] (+%s) = %s" % (self
.Name
, M
.BaseName
, DepexExpressionList
))
3216 if 'BEFORE' in DepexExpressionList
or 'AFTER' in DepexExpressionList
:
3218 if len(DepexExpressionList
) > 0:
3219 EdkLogger
.verbose('')
3220 self
._DepexExpressionList
[ModuleType
] = DepexExpressionList
3221 return self
._DepexExpressionList
3223 # Get the tiano core user extension, it is contain dependent library.
3224 # @retval: a list contain tiano core userextension.
3226 def _GetTianoCoreUserExtensionList(self
):
3227 TianoCoreUserExtentionList
= []
3228 for M
in [self
.Module
] + self
.DependentLibraryList
:
3229 Filename
= M
.MetaFile
.Path
3230 InfObj
= InfSectionParser
.InfSectionParser(Filename
)
3231 TianoCoreUserExtenList
= InfObj
.GetUserExtensionTianoCore()
3232 for TianoCoreUserExtent
in TianoCoreUserExtenList
:
3233 for Section
in TianoCoreUserExtent
:
3234 ItemList
= Section
.split(TAB_SPLIT
)
3236 if len(ItemList
) == 4:
3238 if Arch
.upper() == TAB_ARCH_COMMON
or Arch
.upper() == self
.Arch
.upper():
3240 TianoCoreList
.extend([TAB_SECTION_START
+ Section
+ TAB_SECTION_END
])
3241 TianoCoreList
.extend(TianoCoreUserExtent
[Section
][:])
3242 TianoCoreList
.append('\n')
3243 TianoCoreUserExtentionList
.append(TianoCoreList
)
3245 return TianoCoreUserExtentionList
3247 ## Return the list of specification version required for the module
3249 # @retval list The list of specification defined in module file
3251 def _GetSpecification(self
):
3252 return self
.Module
.Specification
3254 ## Tool option for the module build
3256 # @param PlatformInfo The object of PlatformBuildInfo
3257 # @retval dict The dict containing valid options
3259 def _GetModuleBuildOption(self
):
3260 if self
._BuildOption
is None:
3261 self
._BuildOption
, self
.BuildRuleOrder
= self
.PlatformInfo
.ApplyBuildOption(self
.Module
)
3262 if self
.BuildRuleOrder
:
3263 self
.BuildRuleOrder
= ['.%s' % Ext
for Ext
in self
.BuildRuleOrder
.split()]
3264 return self
._BuildOption
3266 ## Get include path list from tool option for the module build
3268 # @retval list The include path list
3270 def _GetBuildOptionIncPathList(self
):
3271 if self
._BuildOptionIncPathList
is None:
3273 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT
3274 # is the former use /I , the Latter used -I to specify include directories
3276 if self
.PlatformInfo
.ToolChainFamily
in ('MSFT'):
3277 BuildOptIncludeRegEx
= gBuildOptIncludePatternMsft
3278 elif self
.PlatformInfo
.ToolChainFamily
in ('INTEL', 'GCC', 'RVCT'):
3279 BuildOptIncludeRegEx
= gBuildOptIncludePatternOther
3282 # New ToolChainFamily, don't known whether there is option to specify include directories
3284 self
._BuildOptionIncPathList
= []
3285 return self
._BuildOptionIncPathList
3287 BuildOptionIncPathList
= []
3288 for Tool
in ('CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'ASM'):
3291 FlagOption
= self
.BuildOption
[Tool
][Attr
]
3295 if self
.PlatformInfo
.ToolChainFamily
!= 'RVCT':
3296 IncPathList
= [NormPath(Path
, self
.Macros
) for Path
in BuildOptIncludeRegEx
.findall(FlagOption
)]
3299 # RVCT may specify a list of directory seperated by commas
3302 for Path
in BuildOptIncludeRegEx
.findall(FlagOption
):
3303 PathList
= GetSplitList(Path
, TAB_COMMA_SPLIT
)
3304 IncPathList
+= [NormPath(PathEntry
, self
.Macros
) for PathEntry
in PathList
]
3307 # EDK II modules must not reference header files outside of the packages they depend on or
3308 # within the module's directory tree. Report error if violation.
3310 if self
.AutoGenVersion
>= 0x00010005 and len(IncPathList
) > 0:
3311 for Path
in IncPathList
:
3312 if (Path
not in self
.IncludePathList
) and (CommonPath([Path
, self
.MetaFile
.Dir
]) != self
.MetaFile
.Dir
):
3313 ErrMsg
= "The include directory for the EDK II module in this line is invalid %s specified in %s FLAGS '%s'" % (Path
, Tool
, FlagOption
)
3314 EdkLogger
.error("build",
3317 File
=str(self
.MetaFile
))
3320 BuildOptionIncPathList
+= IncPathList
3322 self
._BuildOptionIncPathList
= BuildOptionIncPathList
3324 return self
._BuildOptionIncPathList
3326 ## Return a list of files which can be built from source
3328 # What kind of files can be built is determined by build rules in
3329 # $(CONF_DIRECTORY)/build_rule.txt and toolchain family.
3331 def _GetSourceFileList(self
):
3332 if self
._SourceFileList
is None:
3333 self
._SourceFileList
= []
3334 for F
in self
.Module
.Sources
:
3336 if F
.TagName
not in ("", "*", self
.ToolChain
):
3337 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "The toolchain [%s] for processing file [%s] is found, "
3338 "but [%s] is needed" % (F
.TagName
, str(F
), self
.ToolChain
))
3340 # match tool chain family or build rule family
3341 if F
.ToolChainFamily
not in ("", "*", self
.ToolChainFamily
, self
.BuildRuleFamily
):
3344 "The file [%s] must be built by tools of [%s], " \
3345 "but current toolchain family is [%s], buildrule family is [%s]" \
3346 % (str(F
), F
.ToolChainFamily
, self
.ToolChainFamily
, self
.BuildRuleFamily
))
3349 # add the file path into search path list for file including
3350 if F
.Dir
not in self
.IncludePathList
and self
.AutoGenVersion
>= 0x00010005:
3351 self
.IncludePathList
.insert(0, F
.Dir
)
3352 self
._SourceFileList
.append(F
)
3354 self
._MatchBuildRuleOrder
(self
._SourceFileList
)
3356 for F
in self
._SourceFileList
:
3357 self
._ApplyBuildRule
(F
, TAB_UNKNOWN_FILE
)
3358 return self
._SourceFileList
3360 def _MatchBuildRuleOrder(self
, FileList
):
3362 self
._GetModuleBuildOption
()
3363 for SingleFile
in FileList
:
3364 if self
.BuildRuleOrder
and SingleFile
.Ext
in self
.BuildRuleOrder
and SingleFile
.Ext
in self
.BuildRules
:
3365 key
= SingleFile
.Path
.split(SingleFile
.Ext
)[0]
3366 if key
in Order_Dict
:
3367 Order_Dict
[key
].append(SingleFile
.Ext
)
3369 Order_Dict
[key
] = [SingleFile
.Ext
]
3372 for F
in Order_Dict
:
3373 if len(Order_Dict
[F
]) > 1:
3374 Order_Dict
[F
].sort(key
=lambda i
: self
.BuildRuleOrder
.index(i
))
3375 for Ext
in Order_Dict
[F
][1:]:
3376 RemoveList
.append(F
+ Ext
)
3378 for item
in RemoveList
:
3379 FileList
.remove(item
)
3383 ## Return the list of unicode files
3384 def _GetUnicodeFileList(self
):
3385 if self
._UnicodeFileList
is None:
3386 if TAB_UNICODE_FILE
in self
.FileTypes
:
3387 self
._UnicodeFileList
= self
.FileTypes
[TAB_UNICODE_FILE
]
3389 self
._UnicodeFileList
= []
3390 return self
._UnicodeFileList
3392 ## Return the list of vfr files
3393 def _GetVfrFileList(self
):
3394 if self
._VfrFileList
is None:
3395 if TAB_VFR_FILE
in self
.FileTypes
:
3396 self
._VfrFileList
= self
.FileTypes
[TAB_VFR_FILE
]
3398 self
._VfrFileList
= []
3399 return self
._VfrFileList
3401 ## Return the list of Image Definition files
3402 def _GetIdfFileList(self
):
3403 if self
._IdfFileList
is None:
3404 if TAB_IMAGE_FILE
in self
.FileTypes
:
3405 self
._IdfFileList
= self
.FileTypes
[TAB_IMAGE_FILE
]
3407 self
._IdfFileList
= []
3408 return self
._IdfFileList
3410 ## Return a list of files which can be built from binary
3412 # "Build" binary files are just to copy them to build directory.
3414 # @retval list The list of files which can be built later
3416 def _GetBinaryFiles(self
):
3417 if self
._BinaryFileList
is None:
3418 self
._BinaryFileList
= []
3419 for F
in self
.Module
.Binaries
:
3420 if F
.Target
not in [TAB_ARCH_COMMON
, '*'] and F
.Target
!= self
.BuildTarget
:
3422 self
._BinaryFileList
.append(F
)
3423 self
._ApplyBuildRule
(F
, F
.Type
)
3424 return self
._BinaryFileList
3426 def _GetBuildRules(self
):
3427 if self
._BuildRules
is None:
3429 BuildRuleDatabase
= self
.PlatformInfo
.BuildRule
3430 for Type
in BuildRuleDatabase
.FileTypeList
:
3431 #first try getting build rule by BuildRuleFamily
3432 RuleObject
= BuildRuleDatabase
[Type
, self
.BuildType
, self
.Arch
, self
.BuildRuleFamily
]
3434 # build type is always module type, but ...
3435 if self
.ModuleType
!= self
.BuildType
:
3436 RuleObject
= BuildRuleDatabase
[Type
, self
.ModuleType
, self
.Arch
, self
.BuildRuleFamily
]
3437 #second try getting build rule by ToolChainFamily
3439 RuleObject
= BuildRuleDatabase
[Type
, self
.BuildType
, self
.Arch
, self
.ToolChainFamily
]
3441 # build type is always module type, but ...
3442 if self
.ModuleType
!= self
.BuildType
:
3443 RuleObject
= BuildRuleDatabase
[Type
, self
.ModuleType
, self
.Arch
, self
.ToolChainFamily
]
3446 RuleObject
= RuleObject
.Instantiate(self
.Macros
)
3447 BuildRules
[Type
] = RuleObject
3448 for Ext
in RuleObject
.SourceFileExtList
:
3449 BuildRules
[Ext
] = RuleObject
3450 self
._BuildRules
= BuildRules
3451 return self
._BuildRules
3453 def _ApplyBuildRule(self
, File
, FileType
):
3454 if self
._BuildTargets
is None:
3455 self
._IntroBuildTargetList
= set()
3456 self
._FinalBuildTargetList
= set()
3457 self
._BuildTargets
= defaultdict(set)
3458 self
._FileTypes
= defaultdict(set)
3460 SubDirectory
= os
.path
.join(self
.OutputDir
, File
.SubDir
)
3461 if not os
.path
.exists(SubDirectory
):
3462 CreateDirectory(SubDirectory
)
3468 # Make sure to get build rule order value
3470 self
._GetModuleBuildOption
()
3472 while Index
< len(SourceList
):
3473 Source
= SourceList
[Index
]
3477 CreateDirectory(Source
.Dir
)
3479 if File
.IsBinary
and File
== Source
and self
._BinaryFileList
is not None and File
in self
._BinaryFileList
:
3480 # Skip all files that are not binary libraries
3481 if not self
.IsLibrary
:
3483 RuleObject
= self
.BuildRules
[TAB_DEFAULT_BINARY_FILE
]
3484 elif FileType
in self
.BuildRules
:
3485 RuleObject
= self
.BuildRules
[FileType
]
3486 elif Source
.Ext
in self
.BuildRules
:
3487 RuleObject
= self
.BuildRules
[Source
.Ext
]
3489 # stop at no more rules
3491 self
._FinalBuildTargetList
.add(LastTarget
)
3494 FileType
= RuleObject
.SourceFileType
3495 self
._FileTypes
[FileType
].add(Source
)
3497 # stop at STATIC_LIBRARY for library
3498 if self
.IsLibrary
and FileType
== TAB_STATIC_LIBRARY
:
3500 self
._FinalBuildTargetList
.add(LastTarget
)
3503 Target
= RuleObject
.Apply(Source
, self
.BuildRuleOrder
)
3506 self
._FinalBuildTargetList
.add(LastTarget
)
3508 elif not Target
.Outputs
:
3509 # Only do build for target with outputs
3510 self
._FinalBuildTargetList
.add(Target
)
3512 self
._BuildTargets
[FileType
].add(Target
)
3514 if not Source
.IsBinary
and Source
== File
:
3515 self
._IntroBuildTargetList
.add(Target
)
3517 # to avoid cyclic rule
3518 if FileType
in RuleChain
:
3521 RuleChain
.append(FileType
)
3522 SourceList
.extend(Target
.Outputs
)
3524 FileType
= TAB_UNKNOWN_FILE
3526 def _GetTargets(self
):
3527 if self
._BuildTargets
is None:
3528 self
._IntroBuildTargetList
= set()
3529 self
._FinalBuildTargetList
= set()
3530 self
._BuildTargets
= defaultdict(set)
3531 self
._FileTypes
= defaultdict(set)
3533 #TRICK: call _GetSourceFileList to apply build rule for source files
3534 if self
.SourceFileList
:
3537 #TRICK: call _GetBinaryFileList to apply build rule for binary files
3538 if self
.BinaryFileList
:
3541 return self
._BuildTargets
3543 def _GetIntroTargetList(self
):
3545 return self
._IntroBuildTargetList
3547 def _GetFinalTargetList(self
):
3549 return self
._FinalBuildTargetList
3551 def _GetFileTypes(self
):
3553 return self
._FileTypes
3555 ## Get the list of package object the module depends on
3557 # @retval list The package object list
3559 def _GetDependentPackageList(self
):
3560 return self
.Module
.Packages
3562 ## Return the list of auto-generated code file
3564 # @retval list The list of auto-generated file
3566 def _GetAutoGenFileList(self
):
3567 UniStringAutoGenC
= True
3568 IdfStringAutoGenC
= True
3569 UniStringBinBuffer
= StringIO()
3570 IdfGenBinBuffer
= StringIO()
3571 if self
.BuildType
== 'UEFI_HII':
3572 UniStringAutoGenC
= False
3573 IdfStringAutoGenC
= False
3574 if self
._AutoGenFileList
is None:
3575 self
._AutoGenFileList
= {}
3576 AutoGenC
= TemplateString()
3577 AutoGenH
= TemplateString()
3578 StringH
= TemplateString()
3579 StringIdf
= TemplateString()
3580 GenC
.CreateCode(self
, AutoGenC
, AutoGenH
, StringH
, UniStringAutoGenC
, UniStringBinBuffer
, StringIdf
, IdfStringAutoGenC
, IdfGenBinBuffer
)
3582 # AutoGen.c is generated if there are library classes in inf, or there are object files
3584 if str(AutoGenC
) != "" and (len(self
.Module
.LibraryClasses
) > 0
3585 or TAB_OBJECT_FILE
in self
.FileTypes
):
3586 AutoFile
= PathClass(gAutoGenCodeFileName
, self
.DebugDir
)
3587 self
._AutoGenFileList
[AutoFile
] = str(AutoGenC
)
3588 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3589 if str(AutoGenH
) != "":
3590 AutoFile
= PathClass(gAutoGenHeaderFileName
, self
.DebugDir
)
3591 self
._AutoGenFileList
[AutoFile
] = str(AutoGenH
)
3592 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3593 if str(StringH
) != "":
3594 AutoFile
= PathClass(gAutoGenStringFileName
% {"module_name":self
.Name
}, self
.DebugDir
)
3595 self
._AutoGenFileList
[AutoFile
] = str(StringH
)
3596 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3597 if UniStringBinBuffer
is not None and UniStringBinBuffer
.getvalue() != "":
3598 AutoFile
= PathClass(gAutoGenStringFormFileName
% {"module_name":self
.Name
}, self
.OutputDir
)
3599 self
._AutoGenFileList
[AutoFile
] = UniStringBinBuffer
.getvalue()
3600 AutoFile
.IsBinary
= True
3601 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3602 if UniStringBinBuffer
is not None:
3603 UniStringBinBuffer
.close()
3604 if str(StringIdf
) != "":
3605 AutoFile
= PathClass(gAutoGenImageDefFileName
% {"module_name":self
.Name
}, self
.DebugDir
)
3606 self
._AutoGenFileList
[AutoFile
] = str(StringIdf
)
3607 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3608 if IdfGenBinBuffer
is not None and IdfGenBinBuffer
.getvalue() != "":
3609 AutoFile
= PathClass(gAutoGenIdfFileName
% {"module_name":self
.Name
}, self
.OutputDir
)
3610 self
._AutoGenFileList
[AutoFile
] = IdfGenBinBuffer
.getvalue()
3611 AutoFile
.IsBinary
= True
3612 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3613 if IdfGenBinBuffer
is not None:
3614 IdfGenBinBuffer
.close()
3615 return self
._AutoGenFileList
3617 ## Return the list of library modules explicitly or implicityly used by this module
3618 def _GetLibraryList(self
):
3619 if self
._DependentLibraryList
is None:
3620 # only merge library classes and PCD for non-library module
3622 self
._DependentLibraryList
= []
3624 if self
.AutoGenVersion
< 0x00010005:
3625 self
._DependentLibraryList
= self
.PlatformInfo
.ResolveLibraryReference(self
.Module
)
3627 self
._DependentLibraryList
= self
.PlatformInfo
.ApplyLibraryInstance(self
.Module
)
3628 return self
._DependentLibraryList
3631 def UpdateComments(Recver
, Src
):
3633 if Key
not in Recver
:
3635 Recver
[Key
].extend(Src
[Key
])
3636 ## Get the list of PCDs from current module
3638 # @retval list The list of PCD
3640 def _GetModulePcdList(self
):
3641 if self
._ModulePcdList
is None:
3642 # apply PCD settings from platform
3643 self
._ModulePcdList
= self
.PlatformInfo
.ApplyPcdSetting(self
.Module
, self
.Module
.Pcds
)
3644 self
.UpdateComments(self
._PcdComments
, self
.Module
.PcdComments
)
3645 return self
._ModulePcdList
3647 ## Get the list of PCDs from dependent libraries
3649 # @retval list The list of PCD
3651 def _GetLibraryPcdList(self
):
3652 if self
._LibraryPcdList
is None:
3653 Pcds
= OrderedDict()
3654 if not self
.IsLibrary
:
3655 # get PCDs from dependent libraries
3656 for Library
in self
.DependentLibraryList
:
3657 self
.UpdateComments(self
._PcdComments
, Library
.PcdComments
)
3658 for Key
in Library
.Pcds
:
3659 # skip duplicated PCDs
3660 if Key
in self
.Module
.Pcds
or Key
in Pcds
:
3662 Pcds
[Key
] = copy
.copy(Library
.Pcds
[Key
])
3663 # apply PCD settings from platform
3664 self
._LibraryPcdList
= self
.PlatformInfo
.ApplyPcdSetting(self
.Module
, Pcds
)
3666 self
._LibraryPcdList
= []
3667 return self
._LibraryPcdList
3669 ## Get the GUID value mapping
3671 # @retval dict The mapping between GUID cname and its value
3673 def _GetGuidList(self
):
3674 if self
._GuidList
is None:
3675 self
._GuidList
= OrderedDict()
3676 self
._GuidList
.update(self
.Module
.Guids
)
3677 for Library
in self
.DependentLibraryList
:
3678 self
._GuidList
.update(Library
.Guids
)
3679 self
.UpdateComments(self
._GuidComments
, Library
.GuidComments
)
3680 self
.UpdateComments(self
._GuidComments
, self
.Module
.GuidComments
)
3681 return self
._GuidList
3683 def GetGuidsUsedByPcd(self
):
3684 if self
._GuidsUsedByPcd
is None:
3685 self
._GuidsUsedByPcd
= OrderedDict()
3686 self
._GuidsUsedByPcd
.update(self
.Module
.GetGuidsUsedByPcd())
3687 for Library
in self
.DependentLibraryList
:
3688 self
._GuidsUsedByPcd
.update(Library
.GetGuidsUsedByPcd())
3689 return self
._GuidsUsedByPcd
3690 ## Get the protocol value mapping
3692 # @retval dict The mapping between protocol cname and its value
3694 def _GetProtocolList(self
):
3695 if self
._ProtocolList
is None:
3696 self
._ProtocolList
= OrderedDict()
3697 self
._ProtocolList
.update(self
.Module
.Protocols
)
3698 for Library
in self
.DependentLibraryList
:
3699 self
._ProtocolList
.update(Library
.Protocols
)
3700 self
.UpdateComments(self
._ProtocolComments
, Library
.ProtocolComments
)
3701 self
.UpdateComments(self
._ProtocolComments
, self
.Module
.ProtocolComments
)
3702 return self
._ProtocolList
3704 ## Get the PPI value mapping
3706 # @retval dict The mapping between PPI cname and its value
3708 def _GetPpiList(self
):
3709 if self
._PpiList
is None:
3710 self
._PpiList
= OrderedDict()
3711 self
._PpiList
.update(self
.Module
.Ppis
)
3712 for Library
in self
.DependentLibraryList
:
3713 self
._PpiList
.update(Library
.Ppis
)
3714 self
.UpdateComments(self
._PpiComments
, Library
.PpiComments
)
3715 self
.UpdateComments(self
._PpiComments
, self
.Module
.PpiComments
)
3716 return self
._PpiList
3718 ## Get the list of include search path
3720 # @retval list The list path
3722 def _GetIncludePathList(self
):
3723 if self
._IncludePathList
is None:
3724 self
._IncludePathList
= []
3725 if self
.AutoGenVersion
< 0x00010005:
3726 for Inc
in self
.Module
.Includes
:
3727 if Inc
not in self
._IncludePathList
:
3728 self
._IncludePathList
.append(Inc
)
3730 Inc
= path
.join(Inc
, self
.Arch
.capitalize())
3731 if os
.path
.exists(Inc
) and Inc
not in self
._IncludePathList
:
3732 self
._IncludePathList
.append(Inc
)
3733 # Edk module needs to put DEBUG_DIR at the end of search path and not to use SOURCE_DIR all the time
3734 self
._IncludePathList
.append(self
.DebugDir
)
3736 self
._IncludePathList
.append(self
.MetaFile
.Dir
)
3737 self
._IncludePathList
.append(self
.DebugDir
)
3739 for Package
in self
.Module
.Packages
:
3740 PackageDir
= mws
.join(self
.WorkspaceDir
, Package
.MetaFile
.Dir
)
3741 if PackageDir
not in self
._IncludePathList
:
3742 self
._IncludePathList
.append(PackageDir
)
3743 IncludesList
= Package
.Includes
3744 if Package
._PrivateIncludes
:
3745 if not self
.MetaFile
.Path
.startswith(PackageDir
):
3746 IncludesList
= list(set(Package
.Includes
).difference(set(Package
._PrivateIncludes
)))
3747 for Inc
in IncludesList
:
3748 if Inc
not in self
._IncludePathList
:
3749 self
._IncludePathList
.append(str(Inc
))
3750 return self
._IncludePathList
3752 def _GetIncludePathLength(self
):
3753 self
._IncludePathLength
= 0
3754 if self
._IncludePathList
:
3755 for inc
in self
._IncludePathList
:
3756 self
._IncludePathLength
+= len(' ' + inc
)
3757 return self
._IncludePathLength
3759 ## Get HII EX PCDs which maybe used by VFR
3761 # efivarstore used by VFR may relate with HII EX PCDs
3762 # Get the variable name and GUID from efivarstore and HII EX PCD
3763 # List the HII EX PCDs in As Built INF if both name and GUID match.
3765 # @retval list HII EX PCDs
3767 def _GetPcdsMaybeUsedByVfr(self
):
3768 if not self
.SourceFileList
:
3772 for SrcFile
in self
.SourceFileList
:
3773 if SrcFile
.Ext
.lower() != '.vfr':
3775 Vfri
= os
.path
.join(self
.OutputDir
, SrcFile
.BaseName
+ '.i')
3776 if not os
.path
.exists(Vfri
):
3778 VfriFile
= open(Vfri
, 'r')
3779 Content
= VfriFile
.read()
3781 Pos
= Content
.find('efivarstore')
3784 # Make sure 'efivarstore' is the start of efivarstore statement
3785 # In case of the value of 'name' (name = efivarstore) is equal to 'efivarstore'
3788 while Index
>= 0 and Content
[Index
] in ' \t\r\n':
3790 if Index
>= 0 and Content
[Index
] != ';':
3791 Pos
= Content
.find('efivarstore', Pos
+ len('efivarstore'))
3794 # 'efivarstore' must be followed by name and guid
3796 Name
= gEfiVarStoreNamePattern
.search(Content
, Pos
)
3799 Guid
= gEfiVarStoreGuidPattern
.search(Content
, Pos
)
3802 NameArray
= ConvertStringToByteArray('L"' + Name
.group(1) + '"')
3803 NameGuids
.add((NameArray
, GuidStructureStringToGuidString(Guid
.group(1))))
3804 Pos
= Content
.find('efivarstore', Name
.end())
3808 for Pcd
in self
.PlatformInfo
.Platform
.Pcds
.values():
3809 if Pcd
.Type
!= TAB_PCDS_DYNAMIC_EX_HII
:
3811 for SkuName
in Pcd
.SkuInfoList
:
3812 SkuInfo
= Pcd
.SkuInfoList
[SkuName
]
3813 Name
= ConvertStringToByteArray(SkuInfo
.VariableName
)
3814 Value
= GuidValue(SkuInfo
.VariableGuid
, self
.PlatformInfo
.PackageList
, self
.MetaFile
.Path
)
3817 Guid
= GuidStructureStringToGuidString(Value
)
3818 if (Name
, Guid
) in NameGuids
and Pcd
not in HiiExPcds
:
3819 HiiExPcds
.append(Pcd
)
3824 def _GenOffsetBin(self
):
3826 for SourceFile
in self
.Module
.Sources
:
3827 if SourceFile
.Type
.upper() == ".VFR" :
3829 # search the .map file to find the offset of vfr binary in the PE32+/TE file.
3831 VfrUniBaseName
[SourceFile
.BaseName
] = (SourceFile
.BaseName
+ "Bin")
3832 if SourceFile
.Type
.upper() == ".UNI" :
3834 # search the .map file to find the offset of Uni strings binary in the PE32+/TE file.
3836 VfrUniBaseName
["UniOffsetName"] = (self
.Name
+ "Strings")
3838 if len(VfrUniBaseName
) == 0:
3840 MapFileName
= os
.path
.join(self
.OutputDir
, self
.Name
+ ".map")
3841 EfiFileName
= os
.path
.join(self
.OutputDir
, self
.Name
+ ".efi")
3842 VfrUniOffsetList
= GetVariableOffset(MapFileName
, EfiFileName
, VfrUniBaseName
.values())
3843 if not VfrUniOffsetList
:
3846 OutputName
= '%sOffset.bin' % self
.Name
3847 UniVfrOffsetFileName
= os
.path
.join( self
.OutputDir
, OutputName
)
3850 fInputfile
= open(UniVfrOffsetFileName
, "wb+", 0)
3852 EdkLogger
.error("build", FILE_OPEN_FAILURE
, "File open failed for %s" % UniVfrOffsetFileName
,None)
3854 # Use a instance of StringIO to cache data
3855 fStringIO
= StringIO('')
3857 for Item
in VfrUniOffsetList
:
3858 if (Item
[0].find("Strings") != -1):
3860 # UNI offset in image.
3862 # { 0x8913c5e0, 0x33f6, 0x4d86, { 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66 } }
3864 UniGuid
= [0xe0, 0xc5, 0x13, 0x89, 0xf6, 0x33, 0x86, 0x4d, 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66]
3865 UniGuid
= [chr(ItemGuid
) for ItemGuid
in UniGuid
]
3866 fStringIO
.write(''.join(UniGuid
))
3867 UniValue
= pack ('Q', int (Item
[1], 16))
3868 fStringIO
.write (UniValue
)
3871 # VFR binary offset in image.
3873 # { 0xd0bc7cb4, 0x6a47, 0x495f, { 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2 } };
3875 VfrGuid
= [0xb4, 0x7c, 0xbc, 0xd0, 0x47, 0x6a, 0x5f, 0x49, 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2]
3876 VfrGuid
= [chr(ItemGuid
) for ItemGuid
in VfrGuid
]
3877 fStringIO
.write(''.join(VfrGuid
))
3878 VfrValue
= pack ('Q', int (Item
[1], 16))
3879 fStringIO
.write (VfrValue
)
3881 # write data into file.
3884 fInputfile
.write (fStringIO
.getvalue())
3886 EdkLogger
.error("build", FILE_WRITE_FAILURE
, "Write data to file %s failed, please check whether the "
3887 "file been locked or using by other applications." %UniVfrOffsetFileName
,None)
3893 ## Create AsBuilt INF file the module
3895 def CreateAsBuiltInf(self
, IsOnlyCopy
= False):
3896 self
.OutputFile
= set()
3898 if GlobalData
.gBinCacheDest
:
3899 self
.CopyModuleToCache()
3902 if self
.IsAsBuiltInfCreated
:
3905 # Skip the following code for EDK I inf
3906 if self
.AutoGenVersion
< 0x00010005:
3909 # Skip the following code for libraries
3913 # Skip the following code for modules with no source files
3914 if not self
.SourceFileList
:
3917 # Skip the following code for modules without any binary files
3918 if self
.BinaryFileList
:
3921 ### TODO: How to handles mixed source and binary modules
3923 # Find all DynamicEx and PatchableInModule PCDs used by this module and dependent libraries
3924 # Also find all packages that the DynamicEx PCDs depend on
3929 PcdTokenSpaceList
= []
3930 for Pcd
in self
.ModulePcdList
+ self
.LibraryPcdList
:
3931 if Pcd
.Type
== TAB_PCDS_PATCHABLE_IN_MODULE
:
3932 PatchablePcds
+= [Pcd
]
3933 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, TAB_PCDS_PATCHABLE_IN_MODULE
))
3934 elif Pcd
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
3937 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC_EX
))
3938 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC
))
3939 PcdTokenSpaceList
.append(Pcd
.TokenSpaceGuidCName
)
3940 GuidList
= OrderedDict()
3941 GuidList
.update(self
.GuidList
)
3942 for TokenSpace
in self
.GetGuidsUsedByPcd():
3943 # If token space is not referred by patch PCD or Ex PCD, remove the GUID from GUID list
3944 # The GUIDs in GUIDs section should really be the GUIDs in source INF or referred by Ex an patch PCDs
3945 if TokenSpace
not in PcdTokenSpaceList
and TokenSpace
in GuidList
:
3946 GuidList
.pop(TokenSpace
)
3947 CheckList
= (GuidList
, self
.PpiList
, self
.ProtocolList
, PcdCheckList
)
3948 for Package
in self
.DerivedPackageList
:
3949 if Package
in Packages
:
3951 BeChecked
= (Package
.Guids
, Package
.Ppis
, Package
.Protocols
, Package
.Pcds
)
3953 for Index
in range(len(BeChecked
)):
3954 for Item
in CheckList
[Index
]:
3955 if Item
in BeChecked
[Index
]:
3956 Packages
+= [Package
]
3961 VfrPcds
= self
._GetPcdsMaybeUsedByVfr
()
3962 for Pkg
in self
.PlatformInfo
.PackageList
:
3965 for VfrPcd
in VfrPcds
:
3966 if ((VfrPcd
.TokenCName
, VfrPcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC_EX
) in Pkg
.Pcds
or
3967 (VfrPcd
.TokenCName
, VfrPcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC
) in Pkg
.Pcds
):
3971 ModuleType
= self
.ModuleType
3972 if ModuleType
== SUP_MODULE_UEFI_DRIVER
and self
.DepexGenerated
:
3973 ModuleType
= SUP_MODULE_DXE_DRIVER
3976 if self
.PcdIsDriver
!= '':
3977 DriverType
= self
.PcdIsDriver
3980 MDefs
= self
.Module
.Defines
3983 'module_name' : self
.Name
,
3984 'module_guid' : Guid
,
3985 'module_module_type' : ModuleType
,
3986 'module_version_string' : [MDefs
['VERSION_STRING']] if 'VERSION_STRING' in MDefs
else [],
3987 'pcd_is_driver_string' : [],
3988 'module_uefi_specification_version' : [],
3989 'module_pi_specification_version' : [],
3990 'module_entry_point' : self
.Module
.ModuleEntryPointList
,
3991 'module_unload_image' : self
.Module
.ModuleUnloadImageList
,
3992 'module_constructor' : self
.Module
.ConstructorList
,
3993 'module_destructor' : self
.Module
.DestructorList
,
3994 'module_shadow' : [MDefs
['SHADOW']] if 'SHADOW' in MDefs
else [],
3995 'module_pci_vendor_id' : [MDefs
['PCI_VENDOR_ID']] if 'PCI_VENDOR_ID' in MDefs
else [],
3996 'module_pci_device_id' : [MDefs
['PCI_DEVICE_ID']] if 'PCI_DEVICE_ID' in MDefs
else [],
3997 'module_pci_class_code' : [MDefs
['PCI_CLASS_CODE']] if 'PCI_CLASS_CODE' in MDefs
else [],
3998 'module_pci_revision' : [MDefs
['PCI_REVISION']] if 'PCI_REVISION' in MDefs
else [],
3999 'module_build_number' : [MDefs
['BUILD_NUMBER']] if 'BUILD_NUMBER' in MDefs
else [],
4000 'module_spec' : [MDefs
['SPEC']] if 'SPEC' in MDefs
else [],
4001 'module_uefi_hii_resource_section' : [MDefs
['UEFI_HII_RESOURCE_SECTION']] if 'UEFI_HII_RESOURCE_SECTION' in MDefs
else [],
4002 'module_uni_file' : [MDefs
['MODULE_UNI_FILE']] if 'MODULE_UNI_FILE' in MDefs
else [],
4003 'module_arch' : self
.Arch
,
4004 'package_item' : ['%s' % (Package
.MetaFile
.File
.replace('\\', '/')) for Package
in Packages
],
4006 'patchablepcd_item' : [],
4008 'protocol_item' : [],
4012 'libraryclasses_item' : []
4015 if 'MODULE_UNI_FILE' in MDefs
:
4016 UNIFile
= os
.path
.join(self
.MetaFile
.Dir
, MDefs
['MODULE_UNI_FILE'])
4017 if os
.path
.isfile(UNIFile
):
4018 shutil
.copy2(UNIFile
, self
.OutputDir
)
4020 if self
.AutoGenVersion
> int(gInfSpecVersion
, 0):
4021 AsBuiltInfDict
['module_inf_version'] = '0x%08x' % self
.AutoGenVersion
4023 AsBuiltInfDict
['module_inf_version'] = gInfSpecVersion
4026 AsBuiltInfDict
['pcd_is_driver_string'] += [DriverType
]
4028 if 'UEFI_SPECIFICATION_VERSION' in self
.Specification
:
4029 AsBuiltInfDict
['module_uefi_specification_version'] += [self
.Specification
['UEFI_SPECIFICATION_VERSION']]
4030 if 'PI_SPECIFICATION_VERSION' in self
.Specification
:
4031 AsBuiltInfDict
['module_pi_specification_version'] += [self
.Specification
['PI_SPECIFICATION_VERSION']]
4033 OutputDir
= self
.OutputDir
.replace('\\', '/').strip('/')
4034 DebugDir
= self
.DebugDir
.replace('\\', '/').strip('/')
4035 for Item
in self
.CodaTargetList
:
4036 File
= Item
.Target
.Path
.replace('\\', '/').strip('/').replace(DebugDir
, '').replace(OutputDir
, '').strip('/')
4037 self
.OutputFile
.add(File
)
4038 if os
.path
.isabs(File
):
4039 File
= File
.replace('\\', '/').strip('/').replace(OutputDir
, '').strip('/')
4040 if Item
.Target
.Ext
.lower() == '.aml':
4041 AsBuiltInfDict
['binary_item'] += ['ASL|' + File
]
4042 elif Item
.Target
.Ext
.lower() == '.acpi':
4043 AsBuiltInfDict
['binary_item'] += ['ACPI|' + File
]
4044 elif Item
.Target
.Ext
.lower() == '.efi':
4045 AsBuiltInfDict
['binary_item'] += ['PE32|' + self
.Name
+ '.efi']
4047 AsBuiltInfDict
['binary_item'] += ['BIN|' + File
]
4048 if self
.DepexGenerated
:
4049 self
.OutputFile
.add(self
.Name
+ '.depex')
4050 if self
.ModuleType
in [SUP_MODULE_PEIM
]:
4051 AsBuiltInfDict
['binary_item'] += ['PEI_DEPEX|' + self
.Name
+ '.depex']
4052 if self
.ModuleType
in [SUP_MODULE_DXE_DRIVER
, SUP_MODULE_DXE_RUNTIME_DRIVER
, SUP_MODULE_DXE_SAL_DRIVER
, SUP_MODULE_UEFI_DRIVER
]:
4053 AsBuiltInfDict
['binary_item'] += ['DXE_DEPEX|' + self
.Name
+ '.depex']
4054 if self
.ModuleType
in [SUP_MODULE_DXE_SMM_DRIVER
]:
4055 AsBuiltInfDict
['binary_item'] += ['SMM_DEPEX|' + self
.Name
+ '.depex']
4057 Bin
= self
._GenOffsetBin
()
4059 AsBuiltInfDict
['binary_item'] += ['BIN|%s' % Bin
]
4060 self
.OutputFile
.add(Bin
)
4062 for Root
, Dirs
, Files
in os
.walk(OutputDir
):
4064 if File
.lower().endswith('.pdb'):
4065 AsBuiltInfDict
['binary_item'] += ['DISPOSABLE|' + File
]
4066 self
.OutputFile
.add(File
)
4067 HeaderComments
= self
.Module
.HeaderComments
4069 for Index
in range(len(HeaderComments
)):
4070 if HeaderComments
[Index
].find('@BinaryHeader') != -1:
4071 HeaderComments
[Index
] = HeaderComments
[Index
].replace('@BinaryHeader', '@file')
4074 AsBuiltInfDict
['header_comments'] = '\n'.join(HeaderComments
[StartPos
:]).replace(':#', '://')
4075 AsBuiltInfDict
['tail_comments'] = '\n'.join(self
.Module
.TailComments
)
4078 (self
.ProtocolList
, self
._ProtocolComments
, 'protocol_item'),
4079 (self
.PpiList
, self
._PpiComments
, 'ppi_item'),
4080 (GuidList
, self
._GuidComments
, 'guid_item')
4082 for Item
in GenList
:
4083 for CName
in Item
[0]:
4085 if CName
in Item
[1]:
4086 Comments
= '\n '.join(Item
[1][CName
])
4089 Entry
= Comments
+ '\n ' + CName
4090 AsBuiltInfDict
[Item
[2]].append(Entry
)
4091 PatchList
= parsePcdInfoFromMapFile(
4092 os
.path
.join(self
.OutputDir
, self
.Name
+ '.map'),
4093 os
.path
.join(self
.OutputDir
, self
.Name
+ '.efi')
4096 for Pcd
in PatchablePcds
:
4097 TokenCName
= Pcd
.TokenCName
4098 for PcdItem
in GlobalData
.MixedPcd
:
4099 if (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
4100 TokenCName
= PcdItem
[0]
4102 for PatchPcd
in PatchList
:
4103 if TokenCName
== PatchPcd
[0]:
4108 if Pcd
.DatumType
== 'BOOLEAN':
4109 BoolValue
= Pcd
.DefaultValue
.upper()
4110 if BoolValue
== 'TRUE':
4111 Pcd
.DefaultValue
= '1'
4112 elif BoolValue
== 'FALSE':
4113 Pcd
.DefaultValue
= '0'
4115 if Pcd
.DatumType
in TAB_PCD_NUMERIC_TYPES
:
4116 HexFormat
= '0x%02x'
4117 if Pcd
.DatumType
== TAB_UINT16
:
4118 HexFormat
= '0x%04x'
4119 elif Pcd
.DatumType
== TAB_UINT32
:
4120 HexFormat
= '0x%08x'
4121 elif Pcd
.DatumType
== TAB_UINT64
:
4122 HexFormat
= '0x%016x'
4123 PcdValue
= HexFormat
% int(Pcd
.DefaultValue
, 0)
4125 if Pcd
.MaxDatumSize
is None or Pcd
.MaxDatumSize
== '':
4126 EdkLogger
.error("build", AUTOGEN_ERROR
,
4127 "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
4129 ArraySize
= int(Pcd
.MaxDatumSize
, 0)
4130 PcdValue
= Pcd
.DefaultValue
4131 if PcdValue
[0] != '{':
4133 if PcdValue
[0] == 'L':
4135 PcdValue
= PcdValue
.lstrip('L')
4136 PcdValue
= eval(PcdValue
)
4138 for Index
in range(0, len(PcdValue
)):
4140 CharVal
= ord(PcdValue
[Index
])
4141 NewValue
= NewValue
+ '0x%02x' % (CharVal
& 0x00FF) + ', ' \
4142 + '0x%02x' % (CharVal
>> 8) + ', '
4144 NewValue
= NewValue
+ '0x%02x' % (ord(PcdValue
[Index
]) % 0x100) + ', '
4147 Padding
= Padding
* 2
4148 ArraySize
= ArraySize
/ 2
4149 if ArraySize
< (len(PcdValue
) + 1):
4150 if Pcd
.MaxSizeUserSet
:
4151 EdkLogger
.error("build", AUTOGEN_ERROR
,
4152 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
4155 ArraySize
= len(PcdValue
) + 1
4156 if ArraySize
> len(PcdValue
) + 1:
4157 NewValue
= NewValue
+ Padding
* (ArraySize
- len(PcdValue
) - 1)
4158 PcdValue
= NewValue
+ Padding
.strip().rstrip(',') + '}'
4159 elif len(PcdValue
.split(',')) <= ArraySize
:
4160 PcdValue
= PcdValue
.rstrip('}') + ', 0x00' * (ArraySize
- len(PcdValue
.split(',')))
4163 if Pcd
.MaxSizeUserSet
:
4164 EdkLogger
.error("build", AUTOGEN_ERROR
,
4165 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
4168 ArraySize
= len(PcdValue
) + 1
4169 PcdItem
= '%s.%s|%s|0x%X' % \
4170 (Pcd
.TokenSpaceGuidCName
, TokenCName
, PcdValue
, PatchPcd
[1])
4172 if (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) in self
._PcdComments
:
4173 PcdComments
= '\n '.join(self
._PcdComments
[Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
])
4175 PcdItem
= PcdComments
+ '\n ' + PcdItem
4176 AsBuiltInfDict
['patchablepcd_item'].append(PcdItem
)
4179 for Pcd
in Pcds
+ VfrPcds
:
4184 TokenCName
= Pcd
.TokenCName
4185 for PcdItem
in GlobalData
.MixedPcd
:
4186 if (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
4187 TokenCName
= PcdItem
[0]
4189 if Pcd
.Type
== TAB_PCDS_DYNAMIC_EX_HII
:
4190 for SkuName
in Pcd
.SkuInfoList
:
4191 SkuInfo
= Pcd
.SkuInfoList
[SkuName
]
4192 SkuId
= SkuInfo
.SkuId
4193 HiiInfo
= '## %s|%s|%s' % (SkuInfo
.VariableName
, SkuInfo
.VariableGuid
, SkuInfo
.VariableOffset
)
4197 # Don't generate duplicated HII PCD
4199 if (SkuId
, Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) in HiiPcds
:
4201 HiiPcds
.add((SkuId
, Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
))
4202 if (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) in self
._PcdComments
:
4203 PcdCommentList
= self
._PcdComments
[Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
][:]
4207 for Index
, Comment
in enumerate(PcdCommentList
):
4208 for Usage
in UsageList
:
4209 if Comment
.find(Usage
) != -1:
4213 if UsageIndex
!= -1:
4214 PcdCommentList
[UsageIndex
] = '## %s %s %s' % (UsageStr
, HiiInfo
, PcdCommentList
[UsageIndex
].replace(UsageStr
, ''))
4216 PcdCommentList
.append('## UNDEFINED ' + HiiInfo
)
4217 PcdComments
= '\n '.join(PcdCommentList
)
4218 PcdEntry
= Pcd
.TokenSpaceGuidCName
+ '.' + TokenCName
4220 PcdEntry
= PcdComments
+ '\n ' + PcdEntry
4221 AsBuiltInfDict
['pcd_item'] += [PcdEntry
]
4222 for Item
in self
.BuildOption
:
4223 if 'FLAGS' in self
.BuildOption
[Item
]:
4224 AsBuiltInfDict
['flags_item'] += ['%s:%s_%s_%s_%s_FLAGS = %s' % (self
.ToolChainFamily
, self
.BuildTarget
, self
.ToolChain
, self
.Arch
, Item
, self
.BuildOption
[Item
]['FLAGS'].strip())]
4226 # Generated LibraryClasses section in comments.
4227 for Library
in self
.LibraryAutoGenList
:
4228 AsBuiltInfDict
['libraryclasses_item'] += [Library
.MetaFile
.File
.replace('\\', '/')]
4230 # Generated UserExtensions TianoCore section.
4231 # All tianocore user extensions are copied.
4233 for TianoCore
in self
._GetTianoCoreUserExtensionList
():
4234 UserExtStr
+= '\n'.join(TianoCore
)
4235 ExtensionFile
= os
.path
.join(self
.MetaFile
.Dir
, TianoCore
[1])
4236 if os
.path
.isfile(ExtensionFile
):
4237 shutil
.copy2(ExtensionFile
, self
.OutputDir
)
4238 AsBuiltInfDict
['userextension_tianocore_item'] = UserExtStr
4240 # Generated depex expression section in comments.
4241 AsBuiltInfDict
['depexsection_item'] = ''
4242 DepexExpresion
= self
._GetDepexExpresionString
()
4244 AsBuiltInfDict
['depexsection_item'] = DepexExpresion
4246 AsBuiltInf
= TemplateString()
4247 AsBuiltInf
.Append(gAsBuiltInfHeaderString
.Replace(AsBuiltInfDict
))
4249 SaveFileOnChange(os
.path
.join(self
.OutputDir
, self
.Name
+ '.inf'), str(AsBuiltInf
), False)
4251 self
.IsAsBuiltInfCreated
= True
4252 if GlobalData
.gBinCacheDest
:
4253 self
.CopyModuleToCache()
4255 def CopyModuleToCache(self
):
4256 FileDir
= path
.join(GlobalData
.gBinCacheDest
, self
.Arch
, self
.SourceDir
, self
.MetaFile
.BaseName
)
4257 CreateDirectory (FileDir
)
4258 HashFile
= path
.join(self
.BuildDir
, self
.Name
+ '.hash')
4259 ModuleFile
= path
.join(self
.OutputDir
, self
.Name
+ '.inf')
4260 if os
.path
.exists(HashFile
):
4261 shutil
.copy2(HashFile
, FileDir
)
4262 if os
.path
.exists(ModuleFile
):
4263 shutil
.copy2(ModuleFile
, FileDir
)
4264 if not self
.OutputFile
:
4265 Ma
= self
.Workspace
.BuildDatabase
[PathClass(ModuleFile
), self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
4266 self
.OutputFile
= Ma
.Binaries
4268 for File
in self
.OutputFile
:
4270 if not os
.path
.isabs(File
):
4271 File
= os
.path
.join(self
.OutputDir
, File
)
4272 if os
.path
.exists(File
):
4273 shutil
.copy2(File
, FileDir
)
4275 def AttemptModuleCacheCopy(self
):
4276 if self
.IsBinaryModule
:
4278 FileDir
= path
.join(GlobalData
.gBinCacheSource
, self
.Arch
, self
.SourceDir
, self
.MetaFile
.BaseName
)
4279 HashFile
= path
.join(FileDir
, self
.Name
+ '.hash')
4280 if os
.path
.exists(HashFile
):
4281 f
= open(HashFile
, 'r')
4282 CacheHash
= f
.read()
4284 if GlobalData
.gModuleHash
[self
.Arch
][self
.Name
]:
4285 if CacheHash
== GlobalData
.gModuleHash
[self
.Arch
][self
.Name
]:
4286 for root
, dir, files
in os
.walk(FileDir
):
4288 if self
.Name
+ '.hash' in f
:
4289 shutil
.copy2(HashFile
, self
.BuildDir
)
4291 File
= path
.join(root
, f
)
4292 shutil
.copy2(File
, self
.OutputDir
)
4293 if self
.Name
== "PcdPeim" or self
.Name
== "PcdDxe":
4294 CreatePcdDatabaseCode(self
, TemplateString(), TemplateString())
4298 ## Create makefile for the module and its dependent libraries
4300 # @param CreateLibraryMakeFile Flag indicating if or not the makefiles of
4301 # dependent libraries will be created
4303 def CreateMakeFile(self
, CreateLibraryMakeFile
=True, GenFfsList
= []):
4304 # Ignore generating makefile when it is a binary module
4305 if self
.IsBinaryModule
:
4308 if self
.IsMakeFileCreated
:
4310 self
.GenFfsList
= GenFfsList
4311 if not self
.IsLibrary
and CreateLibraryMakeFile
:
4312 for LibraryAutoGen
in self
.LibraryAutoGenList
:
4313 LibraryAutoGen
.CreateMakeFile()
4318 if len(self
.CustomMakefile
) == 0:
4319 Makefile
= GenMake
.ModuleMakefile(self
)
4321 Makefile
= GenMake
.CustomMakefile(self
)
4322 if Makefile
.Generate():
4323 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated makefile for module %s [%s]" %
4324 (self
.Name
, self
.Arch
))
4326 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Skipped the generation of makefile for module %s [%s]" %
4327 (self
.Name
, self
.Arch
))
4329 self
.CreateTimeStamp(Makefile
)
4330 self
.IsMakeFileCreated
= True
4332 def CopyBinaryFiles(self
):
4333 for File
in self
.Module
.Binaries
:
4335 DstPath
= os
.path
.join(self
.OutputDir
, os
.path
.basename(SrcPath
))
4336 CopyLongFilePath(SrcPath
, DstPath
)
4337 ## Create autogen code for the module and its dependent libraries
4339 # @param CreateLibraryCodeFile Flag indicating if or not the code of
4340 # dependent libraries will be created
4342 def CreateCodeFile(self
, CreateLibraryCodeFile
=True):
4343 if self
.IsCodeFileCreated
:
4346 # Need to generate PcdDatabase even PcdDriver is binarymodule
4347 if self
.IsBinaryModule
and self
.PcdIsDriver
!= '':
4348 CreatePcdDatabaseCode(self
, TemplateString(), TemplateString())
4350 if self
.IsBinaryModule
:
4352 self
.CopyBinaryFiles()
4355 if not self
.IsLibrary
and CreateLibraryCodeFile
:
4356 for LibraryAutoGen
in self
.LibraryAutoGenList
:
4357 LibraryAutoGen
.CreateCodeFile()
4363 IgoredAutoGenList
= []
4365 for File
in self
.AutoGenFileList
:
4366 if GenC
.Generate(File
.Path
, self
.AutoGenFileList
[File
], File
.IsBinary
):
4367 #Ignore Edk AutoGen.c
4368 if self
.AutoGenVersion
< 0x00010005 and File
.Name
== 'AutoGen.c':
4371 AutoGenList
.append(str(File
))
4373 IgoredAutoGenList
.append(str(File
))
4375 # Skip the following code for EDK I inf
4376 if self
.AutoGenVersion
< 0x00010005:
4379 for ModuleType
in self
.DepexList
:
4380 # Ignore empty [depex] section or [depex] section for SUP_MODULE_USER_DEFINED module
4381 if len(self
.DepexList
[ModuleType
]) == 0 or ModuleType
== SUP_MODULE_USER_DEFINED
:
4384 Dpx
= GenDepex
.DependencyExpression(self
.DepexList
[ModuleType
], ModuleType
, True)
4385 DpxFile
= gAutoGenDepexFileName
% {"module_name" : self
.Name
}
4387 if len(Dpx
.PostfixNotation
) <> 0:
4388 self
.DepexGenerated
= True
4390 if Dpx
.Generate(path
.join(self
.OutputDir
, DpxFile
)):
4391 AutoGenList
.append(str(DpxFile
))
4393 IgoredAutoGenList
.append(str(DpxFile
))
4395 if IgoredAutoGenList
== []:
4396 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated [%s] files for module %s [%s]" %
4397 (" ".join(AutoGenList
), self
.Name
, self
.Arch
))
4398 elif AutoGenList
== []:
4399 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Skipped the generation of [%s] files for module %s [%s]" %
4400 (" ".join(IgoredAutoGenList
), self
.Name
, self
.Arch
))
4402 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated [%s] (skipped %s) files for module %s [%s]" %
4403 (" ".join(AutoGenList
), " ".join(IgoredAutoGenList
), self
.Name
, self
.Arch
))
4405 self
.IsCodeFileCreated
= True
4408 ## Summarize the ModuleAutoGen objects of all libraries used by this module
4409 def _GetLibraryAutoGenList(self
):
4410 if self
._LibraryAutoGenList
is None:
4411 self
._LibraryAutoGenList
= []
4412 for Library
in self
.DependentLibraryList
:
4419 self
.PlatformInfo
.MetaFile
4421 if La
not in self
._LibraryAutoGenList
:
4422 self
._LibraryAutoGenList
.append(La
)
4423 for Lib
in La
.CodaTargetList
:
4424 self
._ApplyBuildRule
(Lib
.Target
, TAB_UNKNOWN_FILE
)
4425 return self
._LibraryAutoGenList
4427 def GenModuleHash(self
):
4428 if self
.Arch
not in GlobalData
.gModuleHash
:
4429 GlobalData
.gModuleHash
[self
.Arch
] = {}
4431 # Add Platform level hash
4432 m
.update(GlobalData
.gPlatformHash
)
4433 # Add Package level hash
4434 if self
.DependentPackageList
:
4435 for Pkg
in self
.DependentPackageList
:
4436 if Pkg
.PackageName
in GlobalData
.gPackageHash
[self
.Arch
]:
4437 m
.update(GlobalData
.gPackageHash
[self
.Arch
][Pkg
.PackageName
])
4440 if self
.LibraryAutoGenList
:
4441 for Lib
in self
.LibraryAutoGenList
:
4442 if Lib
.Name
not in GlobalData
.gModuleHash
[self
.Arch
]:
4444 m
.update(GlobalData
.gModuleHash
[self
.Arch
][Lib
.Name
])
4447 f
= open(str(self
.MetaFile
), 'r')
4451 # Add Module's source files
4452 if self
.SourceFileList
:
4453 for File
in self
.SourceFileList
:
4454 f
= open(str(File
), 'r')
4459 ModuleHashFile
= path
.join(self
.BuildDir
, self
.Name
+ ".hash")
4460 if self
.Name
not in GlobalData
.gModuleHash
[self
.Arch
]:
4461 GlobalData
.gModuleHash
[self
.Arch
][self
.Name
] = m
.hexdigest()
4462 if GlobalData
.gBinCacheSource
:
4463 CacheValid
= self
.AttemptModuleCacheCopy()
4466 return SaveFileOnChange(ModuleHashFile
, m
.hexdigest(), True)
4468 ## Decide whether we can skip the ModuleAutoGen process
4469 def CanSkipbyHash(self
):
4470 if GlobalData
.gUseHashCache
:
4471 return not self
.GenModuleHash()
4473 ## Decide whether we can skip the ModuleAutoGen process
4474 # If any source file is newer than the module than we cannot skip
4477 if not os
.path
.exists(self
.GetTimeStampPath()):
4479 #last creation time of the module
4480 DstTimeStamp
= os
.stat(self
.GetTimeStampPath())[8]
4482 SrcTimeStamp
= self
.Workspace
._SrcTimeStamp
4483 if SrcTimeStamp
> DstTimeStamp
:
4486 with
open(self
.GetTimeStampPath(),'r') as f
:
4488 source
= source
.rstrip('\n')
4489 if not os
.path
.exists(source
):
4491 if source
not in ModuleAutoGen
.TimeDict
:
4492 ModuleAutoGen
.TimeDict
[source
] = os
.stat(source
)[8]
4493 if ModuleAutoGen
.TimeDict
[source
] > DstTimeStamp
:
4497 def GetTimeStampPath(self
):
4498 if self
._TimeStampPath
is None:
4499 self
._TimeStampPath
= os
.path
.join(self
.MakeFileDir
, 'AutoGenTimeStamp')
4500 return self
._TimeStampPath
4501 def CreateTimeStamp(self
, Makefile
):
4505 FileSet
.add (self
.MetaFile
.Path
)
4507 for SourceFile
in self
.Module
.Sources
:
4508 FileSet
.add (SourceFile
.Path
)
4510 for Lib
in self
.DependentLibraryList
:
4511 FileSet
.add (Lib
.MetaFile
.Path
)
4513 for f
in self
.AutoGenDepSet
:
4514 FileSet
.add (f
.Path
)
4516 if os
.path
.exists (self
.GetTimeStampPath()):
4517 os
.remove (self
.GetTimeStampPath())
4518 with
open(self
.GetTimeStampPath(), 'w+') as file:
4522 Module
= property(_GetModule
)
4523 Name
= property(_GetBaseName
)
4524 Guid
= property(_GetGuid
)
4525 Version
= property(_GetVersion
)
4526 ModuleType
= property(_GetModuleType
)
4527 ComponentType
= property(_GetComponentType
)
4528 BuildType
= property(_GetBuildType
)
4529 PcdIsDriver
= property(_GetPcdIsDriver
)
4530 AutoGenVersion
= property(_GetAutoGenVersion
)
4531 Macros
= property(_GetMacros
)
4532 Specification
= property(_GetSpecification
)
4534 IsLibrary
= property(_IsLibrary
)
4535 IsBinaryModule
= property(_IsBinaryModule
)
4536 BuildDir
= property(_GetBuildDir
)
4537 OutputDir
= property(_GetOutputDir
)
4538 FfsOutputDir
= property(_GetFfsOutputDir
)
4539 DebugDir
= property(_GetDebugDir
)
4540 MakeFileDir
= property(_GetMakeFileDir
)
4541 CustomMakefile
= property(_GetCustomMakefile
)
4543 IncludePathList
= property(_GetIncludePathList
)
4544 IncludePathLength
= property(_GetIncludePathLength
)
4545 AutoGenFileList
= property(_GetAutoGenFileList
)
4546 UnicodeFileList
= property(_GetUnicodeFileList
)
4547 VfrFileList
= property(_GetVfrFileList
)
4548 SourceFileList
= property(_GetSourceFileList
)
4549 BinaryFileList
= property(_GetBinaryFiles
) # FileType : [File List]
4550 Targets
= property(_GetTargets
)
4551 IntroTargetList
= property(_GetIntroTargetList
)
4552 CodaTargetList
= property(_GetFinalTargetList
)
4553 FileTypes
= property(_GetFileTypes
)
4554 BuildRules
= property(_GetBuildRules
)
4555 IdfFileList
= property(_GetIdfFileList
)
4557 DependentPackageList
= property(_GetDependentPackageList
)
4558 DependentLibraryList
= property(_GetLibraryList
)
4559 LibraryAutoGenList
= property(_GetLibraryAutoGenList
)
4560 DerivedPackageList
= property(_GetDerivedPackageList
)
4562 ModulePcdList
= property(_GetModulePcdList
)
4563 LibraryPcdList
= property(_GetLibraryPcdList
)
4564 GuidList
= property(_GetGuidList
)
4565 ProtocolList
= property(_GetProtocolList
)
4566 PpiList
= property(_GetPpiList
)
4567 DepexList
= property(_GetDepexTokenList
)
4568 DxsFile
= property(_GetDxsFile
)
4569 DepexExpressionList
= property(_GetDepexExpressionTokenList
)
4570 BuildOption
= property(_GetModuleBuildOption
)
4571 BuildOptionIncPathList
= property(_GetBuildOptionIncPathList
)
4572 BuildCommand
= property(_GetBuildCommand
)
4574 FixedAtBuildPcds
= property(_GetFixedAtBuildPcds
)
4576 # This acts like the main() function for the script, unless it is 'import'ed into another script.
4577 if __name__
== '__main__':