2 # Generate AutoGen.h, AutoGen.c and *.depex files
4 # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>
5 # Copyright (c) 2018, Hewlett Packard Enterprise Development, L.P.<BR>
7 # This program and the accompanying materials
8 # are licensed and made available under the terms and conditions of the BSD License
9 # which accompanies this distribution. The full text of the license may be found at
10 # http://opensource.org/licenses/bsd-license.php
12 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
18 from __future__
import print_function
19 from __future__
import absolute_import
20 import Common
.LongFilePathOs
as os
22 import os
.path
as path
28 from . import GenDepex
29 from io
import BytesIO
31 from .StrGather
import *
32 from .BuildEngine
import BuildRule
34 from Common
.LongFilePathSupport
import CopyLongFilePath
35 from Common
.BuildToolError
import *
36 from Common
.DataType
import *
37 from Common
.Misc
import *
38 from Common
.StringUtils
import *
39 import Common
.GlobalData
as GlobalData
40 from GenFds
.FdfParser
import *
41 from CommonDataClass
.CommonClass
import SkuInfoClass
42 from GenPatchPcdTable
.GenPatchPcdTable
import parsePcdInfoFromMapFile
43 import Common
.VpdInfoFile
as VpdInfoFile
44 from .GenPcdDb
import CreatePcdDatabaseCode
45 from Workspace
.MetaFileCommentParser
import UsageList
46 from Workspace
.WorkspaceCommon
import GetModuleLibInstances
47 from Common
.MultipleWorkspace
import MultipleWorkspace
as mws
48 from . import InfSectionParser
51 from .GenVar
import VariableMgr
, var_info
52 from collections
import OrderedDict
53 from collections
import defaultdict
54 from Workspace
.WorkspaceCommon
import OrderedListDict
56 from Common
.caching
import cached_property
, cached_class_function
58 ## Regular expression for splitting Dependency Expression string into tokens
59 gDepexTokenPattern
= re
.compile("(\(|\)|\w+| \S+\.inf)")
61 ## Regular expression for match: PCD(xxxx.yyy)
62 gPCDAsGuidPattern
= re
.compile(r
"^PCD\(.+\..+\)$")
65 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT
66 # is the former use /I , the Latter used -I to specify include directories
68 gBuildOptIncludePatternMsft
= re
.compile(r
"(?:.*?)/I[ \t]*([^ ]*)", re
.MULTILINE | re
.DOTALL
)
69 gBuildOptIncludePatternOther
= re
.compile(r
"(?:.*?)-I[ \t]*([^ ]*)", re
.MULTILINE | re
.DOTALL
)
72 # Match name = variable
74 gEfiVarStoreNamePattern
= re
.compile("\s*name\s*=\s*(\w+)")
76 # The format of guid in efivarstore statement likes following and must be correct:
77 # guid = {0xA04A27f4, 0xDF00, 0x4D42, {0xB5, 0x52, 0x39, 0x51, 0x13, 0x02, 0x11, 0x3D}}
79 gEfiVarStoreGuidPattern
= re
.compile("\s*guid\s*=\s*({.*?{.*?}\s*})")
81 ## Mapping Makefile type
82 gMakeTypeMap
= {TAB_COMPILER_MSFT
:"nmake", "GCC":"gmake"}
85 ## Build rule configuration file
86 gDefaultBuildRuleFile
= 'build_rule.txt'
88 ## Tools definition configuration file
89 gDefaultToolsDefFile
= 'tools_def.txt'
91 ## Build rule default version
92 AutoGenReqBuildRuleVerNum
= "0.1"
94 ## default file name for AutoGen
95 gAutoGenCodeFileName
= "AutoGen.c"
96 gAutoGenHeaderFileName
= "AutoGen.h"
97 gAutoGenStringFileName
= "%(module_name)sStrDefs.h"
98 gAutoGenStringFormFileName
= "%(module_name)sStrDefs.hpk"
99 gAutoGenDepexFileName
= "%(module_name)s.depex"
100 gAutoGenImageDefFileName
= "%(module_name)sImgDefs.h"
101 gAutoGenIdfFileName
= "%(module_name)sIdf.hpk"
102 gInfSpecVersion
= "0x00010017"
105 # Template string to generic AsBuilt INF
107 gAsBuiltInfHeaderString
= TemplateString("""${header_comments}
110 # FILE auto-generated
113 INF_VERSION = ${module_inf_version}
114 BASE_NAME = ${module_name}
115 FILE_GUID = ${module_guid}
116 MODULE_TYPE = ${module_module_type}${BEGIN}
117 VERSION_STRING = ${module_version_string}${END}${BEGIN}
118 PCD_IS_DRIVER = ${pcd_is_driver_string}${END}${BEGIN}
119 UEFI_SPECIFICATION_VERSION = ${module_uefi_specification_version}${END}${BEGIN}
120 PI_SPECIFICATION_VERSION = ${module_pi_specification_version}${END}${BEGIN}
121 ENTRY_POINT = ${module_entry_point}${END}${BEGIN}
122 UNLOAD_IMAGE = ${module_unload_image}${END}${BEGIN}
123 CONSTRUCTOR = ${module_constructor}${END}${BEGIN}
124 DESTRUCTOR = ${module_destructor}${END}${BEGIN}
125 SHADOW = ${module_shadow}${END}${BEGIN}
126 PCI_VENDOR_ID = ${module_pci_vendor_id}${END}${BEGIN}
127 PCI_DEVICE_ID = ${module_pci_device_id}${END}${BEGIN}
128 PCI_CLASS_CODE = ${module_pci_class_code}${END}${BEGIN}
129 PCI_REVISION = ${module_pci_revision}${END}${BEGIN}
130 BUILD_NUMBER = ${module_build_number}${END}${BEGIN}
131 SPEC = ${module_spec}${END}${BEGIN}
132 UEFI_HII_RESOURCE_SECTION = ${module_uefi_hii_resource_section}${END}${BEGIN}
133 MODULE_UNI_FILE = ${module_uni_file}${END}
135 [Packages.${module_arch}]${BEGIN}
136 ${package_item}${END}
138 [Binaries.${module_arch}]${BEGIN}
141 [PatchPcd.${module_arch}]${BEGIN}
145 [Protocols.${module_arch}]${BEGIN}
149 [Ppis.${module_arch}]${BEGIN}
153 [Guids.${module_arch}]${BEGIN}
157 [PcdEx.${module_arch}]${BEGIN}
161 [LibraryClasses.${module_arch}]
162 ## @LIB_INSTANCES${BEGIN}
163 # ${libraryclasses_item}${END}
167 ${userextension_tianocore_item}
171 [BuildOptions.${module_arch}]
173 ## ${flags_item}${END}
176 ## Base class for AutoGen
178 # This class just implements the cache mechanism of AutoGen objects.
180 class AutoGen(object):
181 # database to maintain the objects in each child class
182 __ObjectCache
= {} # (BuildTarget, ToolChain, ARCH, platform file): AutoGen object
186 # @param Class class object of real AutoGen class
187 # (WorkspaceAutoGen, ModuleAutoGen or PlatformAutoGen)
188 # @param Workspace Workspace directory or WorkspaceAutoGen object
189 # @param MetaFile The path of meta file
190 # @param Target Build target
191 # @param Toolchain Tool chain name
192 # @param Arch Target arch
193 # @param *args The specific class related parameters
194 # @param **kwargs The specific class related dict parameters
196 def __new__(cls
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
197 # check if the object has been created
198 Key
= (Target
, Toolchain
, Arch
, MetaFile
)
199 if Key
in cls
.__ObjectCache
:
200 # if it exists, just return it directly
201 return cls
.__ObjectCache
[Key
]
202 # it didnt exist. create it, cache it, then return it
203 RetVal
= cls
.__ObjectCache
[Key
] = super(AutoGen
, cls
).__new
__(cls
)
206 def __init__ (self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
207 super(AutoGen
, self
).__init
__(self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
)
211 # The file path of platform file will be used to represent hash value of this object
213 # @retval int Hash value of the file path of platform file
216 return hash(self
.MetaFile
)
220 # The file path of platform file will be used to represent this object
222 # @retval string String of platform file path
225 return str(self
.MetaFile
)
228 def __eq__(self
, Other
):
229 return Other
and self
.MetaFile
== Other
231 ## Workspace AutoGen class
233 # This class is used mainly to control the whole platform build for different
234 # architecture. This class will generate top level makefile.
236 class WorkspaceAutoGen(AutoGen
):
237 # call super().__init__ then call the worker function with different parameter count
238 def __init__(self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
239 if not hasattr(self
, "_Init"):
240 super(WorkspaceAutoGen
, self
).__init
__(Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
)
241 self
._InitWorker
(Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
)
244 ## Initialize WorkspaceAutoGen
246 # @param WorkspaceDir Root directory of workspace
247 # @param ActivePlatform Meta-file of active platform
248 # @param Target Build target
249 # @param Toolchain Tool chain name
250 # @param ArchList List of architecture of current build
251 # @param MetaFileDb Database containing meta-files
252 # @param BuildConfig Configuration of build
253 # @param ToolDefinition Tool chain definitions
254 # @param FlashDefinitionFile File of flash definition
255 # @param Fds FD list to be generated
256 # @param Fvs FV list to be generated
257 # @param Caps Capsule list to be generated
258 # @param SkuId SKU id from command line
260 def _InitWorker(self
, WorkspaceDir
, ActivePlatform
, Target
, Toolchain
, ArchList
, MetaFileDb
,
261 BuildConfig
, ToolDefinition
, FlashDefinitionFile
='', Fds
=None, Fvs
=None, Caps
=None, SkuId
='', UniFlag
=None,
262 Progress
=None, BuildModule
=None):
263 self
.BuildDatabase
= MetaFileDb
264 self
.MetaFile
= ActivePlatform
265 self
.WorkspaceDir
= WorkspaceDir
266 self
.Platform
= self
.BuildDatabase
[self
.MetaFile
, TAB_ARCH_COMMON
, Target
, Toolchain
]
267 GlobalData
.gActivePlatform
= self
.Platform
268 self
.BuildTarget
= Target
269 self
.ToolChain
= Toolchain
270 self
.ArchList
= ArchList
272 self
.UniFlag
= UniFlag
274 self
.TargetTxt
= BuildConfig
275 self
.ToolDef
= ToolDefinition
276 self
.FdfFile
= FlashDefinitionFile
277 self
.FdTargetList
= Fds
if Fds
else []
278 self
.FvTargetList
= Fvs
if Fvs
else []
279 self
.CapTargetList
= Caps
if Caps
else []
280 self
.AutoGenObjectList
= []
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
424 BuildData
.Pcds
[key
].Pending
= False
426 if BuildData
.MetaFile
in Platform
.Modules
:
427 PlatformModule
= Platform
.Modules
[str(BuildData
.MetaFile
)]
428 if key
in PlatformModule
.Pcds
:
429 PcdInPlatform
= PlatformModule
.Pcds
[key
]
430 if PcdInPlatform
.Type
:
431 BuildData
.Pcds
[key
].Type
= PcdInPlatform
.Type
432 BuildData
.Pcds
[key
].Pending
= False
434 #Pcd used in Library, Pcd Type from reference module if Pcd Type is Pending
435 if BuildData
.Pcds
[key
].Pending
:
436 MGen
= ModuleAutoGen(self
, BuildData
.MetaFile
, Target
, Toolchain
, Arch
, self
.MetaFile
)
437 if MGen
and MGen
.IsLibrary
:
438 if MGen
in PGen
.LibraryAutoGenList
:
439 ReferenceModules
= MGen
.ReferenceModules
440 for ReferenceModule
in ReferenceModules
:
441 if ReferenceModule
.MetaFile
in Platform
.Modules
:
442 RefPlatformModule
= Platform
.Modules
[str(ReferenceModule
.MetaFile
)]
443 if key
in RefPlatformModule
.Pcds
:
444 PcdInReferenceModule
= RefPlatformModule
.Pcds
[key
]
445 if PcdInReferenceModule
.Type
:
446 BuildData
.Pcds
[key
].Type
= PcdInReferenceModule
.Type
447 BuildData
.Pcds
[key
].Pending
= False
450 if TAB_PCDS_DYNAMIC_EX
in BuildData
.Pcds
[key
].Type
:
451 if BuildData
.IsBinaryModule
:
452 BinaryPcdDict
[TAB_PCDS_DYNAMIC_EX
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
454 SourcePcdDict
[TAB_PCDS_DYNAMIC_EX
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
456 elif TAB_PCDS_PATCHABLE_IN_MODULE
in BuildData
.Pcds
[key
].Type
:
457 if BuildData
.MetaFile
.Ext
== '.inf':
458 if BuildData
.IsBinaryModule
:
459 BinaryPcdDict
[TAB_PCDS_PATCHABLE_IN_MODULE
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
461 SourcePcdDict
[TAB_PCDS_PATCHABLE_IN_MODULE
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
463 elif TAB_PCDS_DYNAMIC
in BuildData
.Pcds
[key
].Type
:
464 SourcePcdDict
[TAB_PCDS_DYNAMIC
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
465 elif TAB_PCDS_FIXED_AT_BUILD
in BuildData
.Pcds
[key
].Type
:
466 SourcePcdDict
[TAB_PCDS_FIXED_AT_BUILD
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
470 # A PCD can only use one type for all source modules
472 for i
in SourcePcdDict_Keys
:
473 for j
in SourcePcdDict_Keys
:
475 Intersections
= SourcePcdDict
[i
].intersection(SourcePcdDict
[j
])
476 if len(Intersections
) > 0:
480 "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
),
481 ExtraData
='\n\t'.join(str(P
[1]+'.'+P
[0]) for P
in Intersections
)
485 # intersection the BinaryPCD for Mixed PCD
487 for i
in BinaryPcdDict_Keys
:
488 for j
in BinaryPcdDict_Keys
:
490 Intersections
= BinaryPcdDict
[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
)
503 # intersection the SourcePCD and BinaryPCD for Mixed PCD
505 for i
in SourcePcdDict_Keys
:
506 for j
in BinaryPcdDict_Keys
:
508 Intersections
= SourcePcdDict
[i
].intersection(BinaryPcdDict
[j
])
509 for item
in Intersections
:
510 NewPcd1
= (item
[0] + '_' + i
, item
[1])
511 NewPcd2
= (item
[0] + '_' + j
, item
[1])
512 if item
not in GlobalData
.MixedPcd
:
513 GlobalData
.MixedPcd
[item
] = [NewPcd1
, NewPcd2
]
515 if NewPcd1
not in GlobalData
.MixedPcd
[item
]:
516 GlobalData
.MixedPcd
[item
].append(NewPcd1
)
517 if NewPcd2
not in GlobalData
.MixedPcd
[item
]:
518 GlobalData
.MixedPcd
[item
].append(NewPcd2
)
520 for BuildData
in PGen
.BuildDatabase
._CACHE
_.values():
521 if BuildData
.Arch
!= Arch
:
523 for key
in BuildData
.Pcds
:
524 for SinglePcd
in GlobalData
.MixedPcd
:
525 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) == SinglePcd
:
526 for item
in GlobalData
.MixedPcd
[SinglePcd
]:
527 Pcd_Type
= item
[0].split('_')[-1]
528 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 \
529 (Pcd_Type
== TAB_PCDS_DYNAMIC
and BuildData
.Pcds
[key
].Type
in PCD_DYNAMIC_TYPE_SET
):
530 Value
= BuildData
.Pcds
[key
]
531 Value
.TokenCName
= BuildData
.Pcds
[key
].TokenCName
+ '_' + Pcd_Type
533 newkey
= (Value
.TokenCName
, key
[1])
535 newkey
= (Value
.TokenCName
, key
[1], key
[2])
536 del BuildData
.Pcds
[key
]
537 BuildData
.Pcds
[newkey
] = Value
541 # handle the mixed pcd in FDF file
543 if key
in GlobalData
.MixedPcd
:
546 for item
in GlobalData
.MixedPcd
[key
]:
549 #Collect package set information from INF of FDF
551 for Inf
in ModuleList
:
552 ModuleFile
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, Arch
)
553 if ModuleFile
in Platform
.Modules
:
555 ModuleData
= self
.BuildDatabase
[ModuleFile
, Arch
, Target
, Toolchain
]
556 PkgSet
.update(ModuleData
.Packages
)
557 Pkgs
= list(PkgSet
) + list(PGen
.PackageList
)
562 DecPcds
.add((Pcd
[0], Pcd
[1]))
563 DecPcdsKey
.add((Pcd
[0], Pcd
[1], Pcd
[2]))
565 Platform
.SkuName
= self
.SkuId
566 for Name
, Guid
,Fileds
in PcdSet
:
567 if (Name
, Guid
) not in DecPcds
:
571 "PCD (%s.%s) used in FDF is not declared in DEC files." % (Guid
, Name
),
572 File
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
, Fileds
][0],
573 Line
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
, Fileds
][1]
576 # Check whether Dynamic or DynamicEx PCD used in FDF file. If used, build break and give a error message.
577 if (Name
, Guid
, TAB_PCDS_FIXED_AT_BUILD
) in DecPcdsKey \
578 or (Name
, Guid
, TAB_PCDS_PATCHABLE_IN_MODULE
) in DecPcdsKey \
579 or (Name
, Guid
, TAB_PCDS_FEATURE_FLAG
) in DecPcdsKey
:
581 elif (Name
, Guid
, TAB_PCDS_DYNAMIC
) in DecPcdsKey
or (Name
, Guid
, TAB_PCDS_DYNAMIC_EX
) in DecPcdsKey
:
585 "Using Dynamic or DynamicEx type of PCD [%s.%s] in FDF file is not allowed." % (Guid
, Name
),
586 File
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
, Fileds
][0],
587 Line
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
, Fileds
][1]
590 Pa
= PlatformAutoGen(self
, self
.MetaFile
, Target
, Toolchain
, Arch
)
592 # Explicitly collect platform's dynamic PCDs
594 Pa
.CollectPlatformDynamicPcds()
595 Pa
.CollectFixedAtBuildPcds()
596 self
.AutoGenObjectList
.append(Pa
)
599 # Generate Package level hash value
601 GlobalData
.gPackageHash
[Arch
] = {}
602 if GlobalData
.gUseHashCache
:
604 self
._GenPkgLevelHash
(Pkg
)
607 # Check PCDs token value conflict in each DEC file.
609 self
._CheckAllPcdsTokenValueConflict
()
612 # Check PCD type and definition between DSC and DEC
614 self
._CheckPcdDefineAndType
()
617 # Create BuildOptions Macro & PCD metafile, also add the Active Platform and FDF file.
619 content
= 'gCommandLineDefines: '
620 content
+= str(GlobalData
.gCommandLineDefines
)
621 content
+= os
.linesep
622 content
+= 'BuildOptionPcd: '
623 content
+= str(GlobalData
.BuildOptionPcd
)
624 content
+= os
.linesep
625 content
+= 'Active Platform: '
626 content
+= str(self
.Platform
)
627 content
+= os
.linesep
629 content
+= 'Flash Image Definition: '
630 content
+= str(self
.FdfFile
)
631 content
+= os
.linesep
632 SaveFileOnChange(os
.path
.join(self
.BuildDir
, 'BuildOptions'), content
, False)
635 # Create PcdToken Number file for Dynamic/DynamicEx Pcd.
637 PcdTokenNumber
= 'PcdTokenNumber: '
638 if Pa
.PcdTokenNumber
:
639 if Pa
.DynamicPcdList
:
640 for Pcd
in Pa
.DynamicPcdList
:
641 PcdTokenNumber
+= os
.linesep
642 PcdTokenNumber
+= str((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
))
643 PcdTokenNumber
+= ' : '
644 PcdTokenNumber
+= str(Pa
.PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
])
645 SaveFileOnChange(os
.path
.join(self
.BuildDir
, 'PcdTokenNumber'), PcdTokenNumber
, False)
648 # Get set of workspace metafiles
650 AllWorkSpaceMetaFiles
= self
._GetMetaFiles
(Target
, Toolchain
, Arch
)
653 # Retrieve latest modified time of all metafiles
656 for f
in AllWorkSpaceMetaFiles
:
657 if os
.stat(f
)[8] > SrcTimeStamp
:
658 SrcTimeStamp
= os
.stat(f
)[8]
659 self
._SrcTimeStamp
= SrcTimeStamp
661 if GlobalData
.gUseHashCache
:
663 for files
in AllWorkSpaceMetaFiles
:
664 if files
.endswith('.dec'):
670 SaveFileOnChange(os
.path
.join(self
.BuildDir
, 'AutoGen.hash'), m
.hexdigest(), True)
671 GlobalData
.gPlatformHash
= m
.hexdigest()
674 # Write metafile list to build directory
676 AutoGenFilePath
= os
.path
.join(self
.BuildDir
, 'AutoGen')
677 if os
.path
.exists (AutoGenFilePath
):
678 os
.remove(AutoGenFilePath
)
679 if not os
.path
.exists(self
.BuildDir
):
680 os
.makedirs(self
.BuildDir
)
681 with
open(os
.path
.join(self
.BuildDir
, 'AutoGen'), 'w+') as file:
682 for f
in AllWorkSpaceMetaFiles
:
686 def _GenPkgLevelHash(self
, Pkg
):
687 if Pkg
.PackageName
in GlobalData
.gPackageHash
[Pkg
.Arch
]:
690 PkgDir
= os
.path
.join(self
.BuildDir
, Pkg
.Arch
, Pkg
.PackageName
)
691 CreateDirectory(PkgDir
)
692 HashFile
= os
.path
.join(PkgDir
, Pkg
.PackageName
+ '.hash')
694 # Get .dec file's hash value
695 f
= open(Pkg
.MetaFile
.Path
, 'r')
699 # Get include files hash value
701 for inc
in sorted(Pkg
.Includes
, key
=lambda x
: str(x
)):
702 for Root
, Dirs
, Files
in os
.walk(str(inc
)):
703 for File
in sorted(Files
):
704 File_Path
= os
.path
.join(Root
, File
)
705 f
= open(File_Path
, 'r')
709 SaveFileOnChange(HashFile
, m
.hexdigest(), True)
710 GlobalData
.gPackageHash
[Pkg
.Arch
][Pkg
.PackageName
] = m
.hexdigest()
712 def _GetMetaFiles(self
, Target
, Toolchain
, Arch
):
713 AllWorkSpaceMetaFiles
= set()
718 AllWorkSpaceMetaFiles
.add (self
.FdfFile
.Path
)
719 for f
in GlobalData
.gFdfParser
.GetAllIncludedFile():
720 AllWorkSpaceMetaFiles
.add (f
.FileName
)
724 AllWorkSpaceMetaFiles
.add(self
.MetaFile
.Path
)
727 # add build_rule.txt & tools_def.txt
729 AllWorkSpaceMetaFiles
.add(os
.path
.join(GlobalData
.gConfDirectory
, gDefaultBuildRuleFile
))
730 AllWorkSpaceMetaFiles
.add(os
.path
.join(GlobalData
.gConfDirectory
, gDefaultToolsDefFile
))
732 # add BuildOption metafile
734 AllWorkSpaceMetaFiles
.add(os
.path
.join(self
.BuildDir
, 'BuildOptions'))
736 # add PcdToken Number file for Dynamic/DynamicEx Pcd
738 AllWorkSpaceMetaFiles
.add(os
.path
.join(self
.BuildDir
, 'PcdTokenNumber'))
740 for Arch
in self
.ArchList
:
744 for Package
in PlatformAutoGen(self
, self
.MetaFile
, Target
, Toolchain
, Arch
).PackageList
:
745 AllWorkSpaceMetaFiles
.add(Package
.MetaFile
.Path
)
750 for filePath
in self
.BuildDatabase
[self
.MetaFile
, Arch
, Target
, Toolchain
]._RawData
.IncludedFiles
:
751 AllWorkSpaceMetaFiles
.add(filePath
.Path
)
753 return AllWorkSpaceMetaFiles
755 def _CheckPcdDefineAndType(self
):
756 PcdTypeSet
= {TAB_PCDS_FIXED_AT_BUILD
,
757 TAB_PCDS_PATCHABLE_IN_MODULE
,
758 TAB_PCDS_FEATURE_FLAG
,
762 # This dict store PCDs which are not used by any modules with specified arches
763 UnusedPcd
= OrderedDict()
764 for Pa
in self
.AutoGenObjectList
:
765 # Key of DSC's Pcds dictionary is PcdCName, TokenSpaceGuid
766 for Pcd
in Pa
.Platform
.Pcds
:
767 PcdType
= Pa
.Platform
.Pcds
[Pcd
].Type
769 # If no PCD type, this PCD comes from FDF
773 # Try to remove Hii and Vpd suffix
774 if PcdType
.startswith(TAB_PCDS_DYNAMIC_EX
):
775 PcdType
= TAB_PCDS_DYNAMIC_EX
776 elif PcdType
.startswith(TAB_PCDS_DYNAMIC
):
777 PcdType
= TAB_PCDS_DYNAMIC
779 for Package
in Pa
.PackageList
:
780 # Key of DEC's Pcds dictionary is PcdCName, TokenSpaceGuid, PcdType
781 if (Pcd
[0], Pcd
[1], PcdType
) in Package
.Pcds
:
783 for Type
in PcdTypeSet
:
784 if (Pcd
[0], Pcd
[1], Type
) in Package
.Pcds
:
788 "Type [%s] of PCD [%s.%s] in DSC file doesn't match the type [%s] defined in DEC file." \
789 % (Pa
.Platform
.Pcds
[Pcd
].Type
, Pcd
[1], Pcd
[0], Type
),
794 UnusedPcd
.setdefault(Pcd
, []).append(Pa
.Arch
)
796 for Pcd
in UnusedPcd
:
799 "The PCD was not specified by any INF module in the platform for the given architecture.\n"
800 "\tPCD: [%s.%s]\n\tPlatform: [%s]\n\tArch: %s"
801 % (Pcd
[1], Pcd
[0], os
.path
.basename(str(self
.MetaFile
)), str(UnusedPcd
[Pcd
])),
806 return "%s [%s]" % (self
.MetaFile
, ", ".join(self
.ArchList
))
808 ## Return the directory to store FV files
811 return path
.join(self
.BuildDir
, TAB_FV_DIRECTORY
)
813 ## Return the directory to store all intermediate and final files built
816 return self
.AutoGenObjectList
[0].BuildDir
818 ## Return the build output directory platform specifies
821 return self
.Platform
.OutputDirectory
823 ## Return platform name
826 return self
.Platform
.PlatformName
828 ## Return meta-file GUID
831 return self
.Platform
.Guid
833 ## Return platform version
836 return self
.Platform
.Version
838 ## Return paths of tools
840 def ToolDefinition(self
):
841 return self
.AutoGenObjectList
[0].ToolDefinition
843 ## Return directory of platform makefile
845 # @retval string Makefile directory
848 def MakeFileDir(self
):
851 ## Return build command string
853 # @retval string Build command string
856 def BuildCommand(self
):
857 # BuildCommand should be all the same. So just get one from platform AutoGen
858 return self
.AutoGenObjectList
[0].BuildCommand
860 ## Check the PCDs token value conflict in each DEC file.
862 # Will cause build break and raise error message while two PCDs conflict.
866 def _CheckAllPcdsTokenValueConflict(self
):
867 for Pa
in self
.AutoGenObjectList
:
868 for Package
in Pa
.PackageList
:
869 PcdList
= Package
.Pcds
.values()
870 PcdList
.sort(key
=lambda x
: int(x
.TokenValue
, 0))
872 while (Count
< len(PcdList
) - 1) :
873 Item
= PcdList
[Count
]
874 ItemNext
= PcdList
[Count
+ 1]
876 # Make sure in the same token space the TokenValue should be unique
878 if (int(Item
.TokenValue
, 0) == int(ItemNext
.TokenValue
, 0)):
879 SameTokenValuePcdList
= []
880 SameTokenValuePcdList
.append(Item
)
881 SameTokenValuePcdList
.append(ItemNext
)
882 RemainPcdListLength
= len(PcdList
) - Count
- 2
883 for ValueSameCount
in range(RemainPcdListLength
):
884 if int(PcdList
[len(PcdList
) - RemainPcdListLength
+ ValueSameCount
].TokenValue
, 0) == int(Item
.TokenValue
, 0):
885 SameTokenValuePcdList
.append(PcdList
[len(PcdList
) - RemainPcdListLength
+ ValueSameCount
])
889 # Sort same token value PCD list with TokenGuid and TokenCName
891 SameTokenValuePcdList
.sort(key
=lambda x
: "%s.%s" % (x
.TokenSpaceGuidCName
, x
.TokenCName
))
892 SameTokenValuePcdListCount
= 0
893 while (SameTokenValuePcdListCount
< len(SameTokenValuePcdList
) - 1):
895 TemListItem
= SameTokenValuePcdList
[SameTokenValuePcdListCount
]
896 TemListItemNext
= SameTokenValuePcdList
[SameTokenValuePcdListCount
+ 1]
898 if (TemListItem
.TokenSpaceGuidCName
== TemListItemNext
.TokenSpaceGuidCName
) and (TemListItem
.TokenCName
!= TemListItemNext
.TokenCName
):
899 for PcdItem
in GlobalData
.MixedPcd
:
900 if (TemListItem
.TokenCName
, TemListItem
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
] or \
901 (TemListItemNext
.TokenCName
, TemListItemNext
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
907 "The TokenValue [%s] of PCD [%s.%s] is conflict with: [%s.%s] in %s"\
908 % (TemListItem
.TokenValue
, TemListItem
.TokenSpaceGuidCName
, TemListItem
.TokenCName
, TemListItemNext
.TokenSpaceGuidCName
, TemListItemNext
.TokenCName
, Package
),
911 SameTokenValuePcdListCount
+= 1
912 Count
+= SameTokenValuePcdListCount
915 PcdList
= Package
.Pcds
.values()
916 PcdList
.sort(key
=lambda x
: "%s.%s" % (x
.TokenSpaceGuidCName
, x
.TokenCName
))
918 while (Count
< len(PcdList
) - 1) :
919 Item
= PcdList
[Count
]
920 ItemNext
= PcdList
[Count
+ 1]
922 # Check PCDs with same TokenSpaceGuidCName.TokenCName have same token value as well.
924 if (Item
.TokenSpaceGuidCName
== ItemNext
.TokenSpaceGuidCName
) and (Item
.TokenCName
== ItemNext
.TokenCName
) and (int(Item
.TokenValue
, 0) != int(ItemNext
.TokenValue
, 0)):
928 "The TokenValue [%s] of PCD [%s.%s] in %s defined in two places should be same as well."\
929 % (Item
.TokenValue
, Item
.TokenSpaceGuidCName
, Item
.TokenCName
, Package
),
933 ## Generate fds command
935 def GenFdsCommand(self
):
936 return (GenMake
.TopLevelMakefile(self
)._TEMPLATE
_.Replace(GenMake
.TopLevelMakefile(self
)._TemplateDict
)).strip()
938 ## Create makefile for the platform and modules in it
940 # @param CreateDepsMakeFile Flag indicating if the makefile for
941 # modules will be created as well
943 def CreateMakeFile(self
, CreateDepsMakeFile
=False):
944 if not CreateDepsMakeFile
:
946 for Pa
in self
.AutoGenObjectList
:
947 Pa
.CreateMakeFile(True)
949 ## Create autogen code for platform and modules
951 # Since there's no autogen code for platform, this method will do nothing
952 # if CreateModuleCodeFile is set to False.
954 # @param CreateDepsCodeFile Flag indicating if creating module's
955 # autogen code file or not
957 def CreateCodeFile(self
, CreateDepsCodeFile
=False):
958 if not CreateDepsCodeFile
:
960 for Pa
in self
.AutoGenObjectList
:
961 Pa
.CreateCodeFile(True)
963 ## Create AsBuilt INF file the platform
965 def CreateAsBuiltInf(self
):
969 ## AutoGen class for platform
971 # PlatformAutoGen class will process the original information in platform
972 # file in order to generate makefile for platform.
974 class PlatformAutoGen(AutoGen
):
975 # call super().__init__ then call the worker function with different parameter count
976 def __init__(self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
977 if not hasattr(self
, "_Init"):
978 super(PlatformAutoGen
, self
).__init
__(self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
)
979 self
._InitWorker
(Workspace
, MetaFile
, Target
, Toolchain
, Arch
)
982 # Used to store all PCDs for both PEI and DXE phase, in order to generate
983 # correct PCD database
986 _NonDynaPcdList_
= []
990 # The priority list while override build option
992 PrioList
= {"0x11111" : 16, # TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE (Highest)
993 "0x01111" : 15, # ******_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
994 "0x10111" : 14, # TARGET_*********_ARCH_COMMANDTYPE_ATTRIBUTE
995 "0x00111" : 13, # ******_*********_ARCH_COMMANDTYPE_ATTRIBUTE
996 "0x11011" : 12, # TARGET_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE
997 "0x01011" : 11, # ******_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE
998 "0x10011" : 10, # TARGET_*********_****_COMMANDTYPE_ATTRIBUTE
999 "0x00011" : 9, # ******_*********_****_COMMANDTYPE_ATTRIBUTE
1000 "0x11101" : 8, # TARGET_TOOLCHAIN_ARCH_***********_ATTRIBUTE
1001 "0x01101" : 7, # ******_TOOLCHAIN_ARCH_***********_ATTRIBUTE
1002 "0x10101" : 6, # TARGET_*********_ARCH_***********_ATTRIBUTE
1003 "0x00101" : 5, # ******_*********_ARCH_***********_ATTRIBUTE
1004 "0x11001" : 4, # TARGET_TOOLCHAIN_****_***********_ATTRIBUTE
1005 "0x01001" : 3, # ******_TOOLCHAIN_****_***********_ATTRIBUTE
1006 "0x10001" : 2, # TARGET_*********_****_***********_ATTRIBUTE
1007 "0x00001" : 1} # ******_*********_****_***********_ATTRIBUTE (Lowest)
1009 ## Initialize PlatformAutoGen
1012 # @param Workspace WorkspaceAutoGen object
1013 # @param PlatformFile Platform file (DSC file)
1014 # @param Target Build target (DEBUG, RELEASE)
1015 # @param Toolchain Name of tool chain
1016 # @param Arch arch of the platform supports
1018 def _InitWorker(self
, Workspace
, PlatformFile
, Target
, Toolchain
, Arch
):
1019 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "AutoGen platform [%s] [%s]" % (PlatformFile
, Arch
))
1020 GlobalData
.gProcessingFile
= "%s [%s, %s, %s]" % (PlatformFile
, Arch
, Toolchain
, Target
)
1022 self
.MetaFile
= PlatformFile
1023 self
.Workspace
= Workspace
1024 self
.WorkspaceDir
= Workspace
.WorkspaceDir
1025 self
.ToolChain
= Toolchain
1026 self
.BuildTarget
= Target
1028 self
.SourceDir
= PlatformFile
.SubDir
1029 self
.SourceOverrideDir
= None
1030 self
.FdTargetList
= self
.Workspace
.FdTargetList
1031 self
.FvTargetList
= self
.Workspace
.FvTargetList
1032 self
.AllPcdList
= []
1033 # get the original module/package/platform objects
1034 self
.BuildDatabase
= Workspace
.BuildDatabase
1035 self
.DscBuildDataObj
= Workspace
.Platform
1037 # flag indicating if the makefile/C-code file has been created or not
1038 self
.IsMakeFileCreated
= False
1040 self
._DynamicPcdList
= None # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
1041 self
._NonDynamicPcdList
= None # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
1043 self
._AsBuildInfList
= []
1044 self
._AsBuildModuleList
= []
1046 self
.VariableInfo
= None
1048 if GlobalData
.gFdfParser
is not None:
1049 self
._AsBuildInfList
= GlobalData
.gFdfParser
.Profile
.InfList
1050 for Inf
in self
._AsBuildInfList
:
1051 InfClass
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, self
.Arch
)
1052 M
= self
.BuildDatabase
[InfClass
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1053 if not M
.IsBinaryModule
:
1055 self
._AsBuildModuleList
.append(InfClass
)
1056 # get library/modules for build
1057 self
.LibraryBuildDirectoryList
= []
1058 self
.ModuleBuildDirectoryList
= []
1062 @cached_class_function
1064 return "%s [%s]" % (self
.MetaFile
, self
.Arch
)
1066 ## Create autogen code for platform and modules
1068 # Since there's no autogen code for platform, this method will do nothing
1069 # if CreateModuleCodeFile is set to False.
1071 # @param CreateModuleCodeFile Flag indicating if creating module's
1072 # autogen code file or not
1074 @cached_class_function
1075 def CreateCodeFile(self
, CreateModuleCodeFile
=False):
1076 # only module has code to be greated, so do nothing if CreateModuleCodeFile is False
1077 if not CreateModuleCodeFile
:
1080 for Ma
in self
.ModuleAutoGenList
:
1081 Ma
.CreateCodeFile(True)
1083 ## Generate Fds Command
1085 def GenFdsCommand(self
):
1086 return self
.Workspace
.GenFdsCommand
1088 ## Create makefile for the platform and modules in it
1090 # @param CreateModuleMakeFile Flag indicating if the makefile for
1091 # modules will be created as well
1093 def CreateMakeFile(self
, CreateModuleMakeFile
=False, FfsCommand
= {}):
1094 if CreateModuleMakeFile
:
1095 for Ma
in self
._MaList
:
1096 key
= (Ma
.MetaFile
.File
, self
.Arch
)
1097 if key
in FfsCommand
:
1098 Ma
.CreateMakeFile(True, FfsCommand
[key
])
1100 Ma
.CreateMakeFile(True)
1102 # no need to create makefile for the platform more than once
1103 if self
.IsMakeFileCreated
:
1106 # create library/module build dirs for platform
1107 Makefile
= GenMake
.PlatformMakefile(self
)
1108 self
.LibraryBuildDirectoryList
= Makefile
.GetLibraryBuildDirectoryList()
1109 self
.ModuleBuildDirectoryList
= Makefile
.GetModuleBuildDirectoryList()
1111 self
.IsMakeFileCreated
= True
1113 ## Deal with Shared FixedAtBuild Pcds
1115 def CollectFixedAtBuildPcds(self
):
1116 for LibAuto
in self
.LibraryAutoGenList
:
1117 FixedAtBuildPcds
= {}
1118 ShareFixedAtBuildPcdsSameValue
= {}
1119 for Module
in LibAuto
.ReferenceModules
:
1120 for Pcd
in set(Module
.FixedAtBuildPcds
+ LibAuto
.FixedAtBuildPcds
):
1121 DefaultValue
= Pcd
.DefaultValue
1122 # Cover the case: DSC component override the Pcd value and the Pcd only used in one Lib
1123 if Pcd
in Module
.LibraryPcdList
:
1124 Index
= Module
.LibraryPcdList
.index(Pcd
)
1125 DefaultValue
= Module
.LibraryPcdList
[Index
].DefaultValue
1126 key
= ".".join((Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
))
1127 if key
not in FixedAtBuildPcds
:
1128 ShareFixedAtBuildPcdsSameValue
[key
] = True
1129 FixedAtBuildPcds
[key
] = DefaultValue
1131 if FixedAtBuildPcds
[key
] != DefaultValue
:
1132 ShareFixedAtBuildPcdsSameValue
[key
] = False
1133 for Pcd
in LibAuto
.FixedAtBuildPcds
:
1134 key
= ".".join((Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
))
1135 if (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
) not in self
.NonDynamicPcdDict
:
1138 DscPcd
= self
.NonDynamicPcdDict
[(Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
)]
1139 if DscPcd
.Type
!= TAB_PCDS_FIXED_AT_BUILD
:
1141 if key
in ShareFixedAtBuildPcdsSameValue
and ShareFixedAtBuildPcdsSameValue
[key
]:
1142 LibAuto
.ConstPcd
[key
] = FixedAtBuildPcds
[key
]
1144 def CollectVariables(self
, DynamicPcdSet
):
1147 if self
.Workspace
.FdfFile
:
1148 FdDict
= self
.Workspace
.FdfProfile
.FdDict
[GlobalData
.gFdfParser
.CurrentFdName
]
1149 for FdRegion
in FdDict
.RegionList
:
1150 for item
in FdRegion
.RegionDataList
:
1151 if self
.Platform
.VpdToolGuid
.strip() and self
.Platform
.VpdToolGuid
in item
:
1152 VpdRegionSize
= FdRegion
.Size
1153 VpdRegionBase
= FdRegion
.Offset
1156 VariableInfo
= VariableMgr(self
.DscBuildDataObj
._GetDefaultStores
(), self
.DscBuildDataObj
.SkuIds
)
1157 VariableInfo
.SetVpdRegionMaxSize(VpdRegionSize
)
1158 VariableInfo
.SetVpdRegionOffset(VpdRegionBase
)
1160 for Pcd
in DynamicPcdSet
:
1161 pcdname
= ".".join((Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
))
1162 for SkuName
in Pcd
.SkuInfoList
:
1163 Sku
= Pcd
.SkuInfoList
[SkuName
]
1165 if SkuId
is None or SkuId
== '':
1167 if len(Sku
.VariableName
) > 0:
1168 if Sku
.VariableAttribute
and 'NV' not in Sku
.VariableAttribute
:
1170 VariableGuidStructure
= Sku
.VariableGuidValue
1171 VariableGuid
= GuidStructureStringToGuidString(VariableGuidStructure
)
1172 for StorageName
in Sku
.DefaultStoreDict
:
1173 VariableInfo
.append_variable(var_info(Index
, pcdname
, StorageName
, SkuName
, StringToArray(Sku
.VariableName
), VariableGuid
, Sku
.VariableOffset
, Sku
.VariableAttribute
, Sku
.HiiDefaultValue
, Sku
.DefaultStoreDict
[StorageName
] if Pcd
.DatumType
in TAB_PCD_NUMERIC_TYPES
else StringToArray(Sku
.DefaultStoreDict
[StorageName
]), Pcd
.DatumType
, Pcd
.CustomAttribute
['DscPosition'], Pcd
.CustomAttribute
.get('IsStru',False)))
1177 def UpdateNVStoreMaxSize(self
, OrgVpdFile
):
1178 if self
.VariableInfo
:
1179 VpdMapFilePath
= os
.path
.join(self
.BuildDir
, TAB_FV_DIRECTORY
, "%s.map" % self
.Platform
.VpdToolGuid
)
1180 PcdNvStoreDfBuffer
= [item
for item
in self
._DynamicPcdList
if item
.TokenCName
== "PcdNvStoreDefaultValueBuffer" and item
.TokenSpaceGuidCName
== "gEfiMdeModulePkgTokenSpaceGuid"]
1182 if PcdNvStoreDfBuffer
:
1183 if os
.path
.exists(VpdMapFilePath
):
1184 OrgVpdFile
.Read(VpdMapFilePath
)
1185 PcdItems
= OrgVpdFile
.GetOffset(PcdNvStoreDfBuffer
[0])
1186 NvStoreOffset
= PcdItems
.values()[0].strip() if PcdItems
else '0'
1188 EdkLogger
.error("build", FILE_READ_FAILURE
, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath
)
1190 NvStoreOffset
= int(NvStoreOffset
, 16) if NvStoreOffset
.upper().startswith("0X") else int(NvStoreOffset
)
1191 default_skuobj
= PcdNvStoreDfBuffer
[0].SkuInfoList
.get(TAB_DEFAULT
)
1192 maxsize
= self
.VariableInfo
.VpdRegionSize
- NvStoreOffset
if self
.VariableInfo
.VpdRegionSize
else len(default_skuobj
.DefaultValue
.split(","))
1193 var_data
= self
.VariableInfo
.PatchNVStoreDefaultMaxSize(maxsize
)
1195 if var_data
and default_skuobj
:
1196 default_skuobj
.DefaultValue
= var_data
1197 PcdNvStoreDfBuffer
[0].DefaultValue
= var_data
1198 PcdNvStoreDfBuffer
[0].SkuInfoList
.clear()
1199 PcdNvStoreDfBuffer
[0].SkuInfoList
[TAB_DEFAULT
] = default_skuobj
1200 PcdNvStoreDfBuffer
[0].MaxDatumSize
= str(len(default_skuobj
.DefaultValue
.split(",")))
1204 ## Collect dynamic PCDs
1206 # Gather dynamic PCDs list from each module and their settings from platform
1207 # This interface should be invoked explicitly when platform action is created.
1209 def CollectPlatformDynamicPcds(self
):
1210 for key
in self
.Platform
.Pcds
:
1211 for SinglePcd
in GlobalData
.MixedPcd
:
1212 if (self
.Platform
.Pcds
[key
].TokenCName
, self
.Platform
.Pcds
[key
].TokenSpaceGuidCName
) == SinglePcd
:
1213 for item
in GlobalData
.MixedPcd
[SinglePcd
]:
1214 Pcd_Type
= item
[0].split('_')[-1]
1215 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 \
1216 (Pcd_Type
== TAB_PCDS_DYNAMIC
and self
.Platform
.Pcds
[key
].Type
in PCD_DYNAMIC_TYPE_SET
):
1217 Value
= self
.Platform
.Pcds
[key
]
1218 Value
.TokenCName
= self
.Platform
.Pcds
[key
].TokenCName
+ '_' + Pcd_Type
1220 newkey
= (Value
.TokenCName
, key
[1])
1222 newkey
= (Value
.TokenCName
, key
[1], key
[2])
1223 del self
.Platform
.Pcds
[key
]
1224 self
.Platform
.Pcds
[newkey
] = Value
1228 # for gathering error information
1229 NoDatumTypePcdList
= set()
1231 for InfName
in self
._AsBuildInfList
:
1232 InfName
= mws
.join(self
.WorkspaceDir
, InfName
)
1233 FdfModuleList
.append(os
.path
.normpath(InfName
))
1234 for M
in self
._MaList
:
1235 # F is the Module for which M is the module autogen
1236 for PcdFromModule
in M
.ModulePcdList
+ M
.LibraryPcdList
:
1237 # make sure that the "VOID*" kind of datum has MaxDatumSize set
1238 if PcdFromModule
.DatumType
== TAB_VOID
and not PcdFromModule
.MaxDatumSize
:
1239 NoDatumTypePcdList
.add("%s.%s [%s]" % (PcdFromModule
.TokenSpaceGuidCName
, PcdFromModule
.TokenCName
, M
.MetaFile
))
1241 # Check the PCD from Binary INF or Source INF
1242 if M
.IsBinaryModule
== True:
1243 PcdFromModule
.IsFromBinaryInf
= True
1245 # Check the PCD from DSC or not
1246 PcdFromModule
.IsFromDsc
= (PcdFromModule
.TokenCName
, PcdFromModule
.TokenSpaceGuidCName
) in self
.Platform
.Pcds
1248 if PcdFromModule
.Type
in PCD_DYNAMIC_TYPE_SET
or PcdFromModule
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
1249 if M
.MetaFile
.Path
not in FdfModuleList
:
1250 # If one of the Source built modules listed in the DSC is not listed
1251 # in FDF modules, and the INF lists a PCD can only use the PcdsDynamic
1252 # access method (it is only listed in the DEC file that declares the
1253 # PCD as PcdsDynamic), then build tool will report warning message
1254 # notify the PI that they are attempting to build a module that must
1255 # be included in a flash image in order to be functional. These Dynamic
1256 # PCD will not be added into the Database unless it is used by other
1257 # modules that are included in the FDF file.
1258 if PcdFromModule
.Type
in PCD_DYNAMIC_TYPE_SET
and \
1259 PcdFromModule
.IsFromBinaryInf
== False:
1260 # Print warning message to let the developer make a determine.
1262 # If one of the Source built modules listed in the DSC is not listed in
1263 # FDF modules, and the INF lists a PCD can only use the PcdsDynamicEx
1264 # access method (it is only listed in the DEC file that declares the
1265 # PCD as PcdsDynamicEx), then DO NOT break the build; DO NOT add the
1266 # PCD to the Platform's PCD Database.
1267 if PcdFromModule
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
1270 # If a dynamic PCD used by a PEM module/PEI module & DXE module,
1271 # it should be stored in Pcd PEI database, If a dynamic only
1272 # used by DXE module, it should be stored in DXE PCD database.
1273 # The default Phase is DXE
1275 if M
.ModuleType
in SUP_MODULE_SET_PEI
:
1276 PcdFromModule
.Phase
= "PEI"
1277 if PcdFromModule
not in self
._DynaPcdList
_:
1278 self
._DynaPcdList
_.append(PcdFromModule
)
1279 elif PcdFromModule
.Phase
== 'PEI':
1280 # overwrite any the same PCD existing, if Phase is PEI
1281 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1282 self
._DynaPcdList
_[Index
] = PcdFromModule
1283 elif PcdFromModule
not in self
._NonDynaPcdList
_:
1284 self
._NonDynaPcdList
_.append(PcdFromModule
)
1285 elif PcdFromModule
in self
._NonDynaPcdList
_ and PcdFromModule
.IsFromBinaryInf
== True:
1286 Index
= self
._NonDynaPcdList
_.index(PcdFromModule
)
1287 if self
._NonDynaPcdList
_[Index
].IsFromBinaryInf
== False:
1288 #The PCD from Binary INF will override the same one from source INF
1289 self
._NonDynaPcdList
_.remove (self
._NonDynaPcdList
_[Index
])
1290 PcdFromModule
.Pending
= False
1291 self
._NonDynaPcdList
_.append (PcdFromModule
)
1292 DscModuleSet
= {os
.path
.normpath(ModuleInf
.Path
) for ModuleInf
in self
.Platform
.Modules
}
1293 # add the PCD from modules that listed in FDF but not in DSC to Database
1294 for InfName
in FdfModuleList
:
1295 if InfName
not in DscModuleSet
:
1296 InfClass
= PathClass(InfName
)
1297 M
= self
.BuildDatabase
[InfClass
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1298 # If a module INF in FDF but not in current arch's DSC module list, it must be module (either binary or source)
1299 # for different Arch. PCDs in source module for different Arch is already added before, so skip the source module here.
1300 # For binary module, if in current arch, we need to list the PCDs into database.
1301 if not M
.IsBinaryModule
:
1303 # Override the module PCD setting by platform setting
1304 ModulePcdList
= self
.ApplyPcdSetting(M
, M
.Pcds
)
1305 for PcdFromModule
in ModulePcdList
:
1306 PcdFromModule
.IsFromBinaryInf
= True
1307 PcdFromModule
.IsFromDsc
= False
1308 # Only allow the DynamicEx and Patchable PCD in AsBuild INF
1309 if PcdFromModule
.Type
not in PCD_DYNAMIC_EX_TYPE_SET
and PcdFromModule
.Type
not in TAB_PCDS_PATCHABLE_IN_MODULE
:
1310 EdkLogger
.error("build", AUTOGEN_ERROR
, "PCD setting error",
1312 ExtraData
="\n\tExisted %s PCD %s in:\n\t\t%s\n"
1313 % (PcdFromModule
.Type
, PcdFromModule
.TokenCName
, InfName
))
1314 # make sure that the "VOID*" kind of datum has MaxDatumSize set
1315 if PcdFromModule
.DatumType
== TAB_VOID
and not PcdFromModule
.MaxDatumSize
:
1316 NoDatumTypePcdList
.add("%s.%s [%s]" % (PcdFromModule
.TokenSpaceGuidCName
, PcdFromModule
.TokenCName
, InfName
))
1317 if M
.ModuleType
in SUP_MODULE_SET_PEI
:
1318 PcdFromModule
.Phase
= "PEI"
1319 if PcdFromModule
not in self
._DynaPcdList
_ and PcdFromModule
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
1320 self
._DynaPcdList
_.append(PcdFromModule
)
1321 elif PcdFromModule
not in self
._NonDynaPcdList
_ and PcdFromModule
.Type
in TAB_PCDS_PATCHABLE_IN_MODULE
:
1322 self
._NonDynaPcdList
_.append(PcdFromModule
)
1323 if PcdFromModule
in self
._DynaPcdList
_ and PcdFromModule
.Phase
== 'PEI' and PcdFromModule
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
1324 # Overwrite the phase of any the same PCD existing, if Phase is PEI.
1325 # It is to solve the case that a dynamic PCD used by a PEM module/PEI
1326 # module & DXE module at a same time.
1327 # Overwrite the type of the PCDs in source INF by the type of AsBuild
1328 # INF file as DynamicEx.
1329 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1330 self
._DynaPcdList
_[Index
].Phase
= PcdFromModule
.Phase
1331 self
._DynaPcdList
_[Index
].Type
= PcdFromModule
.Type
1332 for PcdFromModule
in self
._NonDynaPcdList
_:
1333 # If a PCD is not listed in the DSC file, but binary INF files used by
1334 # this platform all (that use this PCD) list the PCD in a [PatchPcds]
1335 # section, AND all source INF files used by this platform the build
1336 # that use the PCD list the PCD in either a [Pcds] or [PatchPcds]
1337 # section, then the tools must NOT add the PCD to the Platform's PCD
1338 # Database; the build must assign the access method for this PCD as
1339 # PcdsPatchableInModule.
1340 if PcdFromModule
not in self
._DynaPcdList
_:
1342 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1343 if PcdFromModule
.IsFromDsc
== False and \
1344 PcdFromModule
.Type
in TAB_PCDS_PATCHABLE_IN_MODULE
and \
1345 PcdFromModule
.IsFromBinaryInf
== True and \
1346 self
._DynaPcdList
_[Index
].IsFromBinaryInf
== False:
1347 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1348 self
._DynaPcdList
_.remove (self
._DynaPcdList
_[Index
])
1350 # print out error information and break the build, if error found
1351 if len(NoDatumTypePcdList
) > 0:
1352 NoDatumTypePcdListString
= "\n\t\t".join(NoDatumTypePcdList
)
1353 EdkLogger
.error("build", AUTOGEN_ERROR
, "PCD setting error",
1355 ExtraData
="\n\tPCD(s) without MaxDatumSize:\n\t\t%s\n"
1356 % NoDatumTypePcdListString
)
1357 self
._NonDynamicPcdList
= self
._NonDynaPcdList
_
1358 self
._DynamicPcdList
= self
._DynaPcdList
_
1360 # Sort dynamic PCD list to:
1361 # 1) If PCD's datum type is VOID* and value is unicode string which starts with L, the PCD item should
1362 # try to be put header of dynamicd List
1363 # 2) If PCD is HII type, the PCD item should be put after unicode type PCD
1365 # The reason of sorting is make sure the unicode string is in double-byte alignment in string table.
1367 UnicodePcdArray
= set()
1369 OtherPcdArray
= set()
1371 VpdFile
= VpdInfoFile
.VpdInfoFile()
1372 NeedProcessVpdMapFile
= False
1374 for pcd
in self
.Platform
.Pcds
:
1375 if pcd
not in self
._PlatformPcds
:
1376 self
._PlatformPcds
[pcd
] = self
.Platform
.Pcds
[pcd
]
1378 for item
in self
._PlatformPcds
:
1379 if self
._PlatformPcds
[item
].DatumType
and self
._PlatformPcds
[item
].DatumType
not in [TAB_UINT8
, TAB_UINT16
, TAB_UINT32
, TAB_UINT64
, TAB_VOID
, "BOOLEAN"]:
1380 self
._PlatformPcds
[item
].DatumType
= TAB_VOID
1382 if (self
.Workspace
.ArchList
[-1] == self
.Arch
):
1383 for Pcd
in self
._DynamicPcdList
:
1384 # just pick the a value to determine whether is unicode string type
1385 Sku
= Pcd
.SkuInfoList
.values()[0]
1386 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1388 if Pcd
.DatumType
not in [TAB_UINT8
, TAB_UINT16
, TAB_UINT32
, TAB_UINT64
, TAB_VOID
, "BOOLEAN"]:
1389 Pcd
.DatumType
= TAB_VOID
1391 # if found PCD which datum value is unicode string the insert to left size of UnicodeIndex
1392 # if found HII type PCD then insert to right of UnicodeIndex
1393 if Pcd
.Type
in [TAB_PCDS_DYNAMIC_VPD
, TAB_PCDS_DYNAMIC_EX_VPD
]:
1394 VpdPcdDict
[(Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
)] = Pcd
1396 #Collect DynamicHii PCD values and assign it to DynamicExVpd PCD gEfiMdeModulePkgTokenSpaceGuid.PcdNvStoreDefaultValueBuffer
1397 PcdNvStoreDfBuffer
= VpdPcdDict
.get(("PcdNvStoreDefaultValueBuffer", "gEfiMdeModulePkgTokenSpaceGuid"))
1398 if PcdNvStoreDfBuffer
:
1399 self
.VariableInfo
= self
.CollectVariables(self
._DynamicPcdList
)
1400 vardump
= self
.VariableInfo
.dump()
1402 PcdNvStoreDfBuffer
.DefaultValue
= vardump
1403 for skuname
in PcdNvStoreDfBuffer
.SkuInfoList
:
1404 PcdNvStoreDfBuffer
.SkuInfoList
[skuname
].DefaultValue
= vardump
1405 PcdNvStoreDfBuffer
.MaxDatumSize
= str(len(vardump
.split(",")))
1407 #If the end user define [DefaultStores] and [XXX.Menufacturing] in DSC, but forget to configure PcdNvStoreDefaultValueBuffer to PcdsDynamicVpd
1408 if [Pcd
for Pcd
in self
._DynamicPcdList
if Pcd
.UserDefinedDefaultStoresFlag
]:
1409 EdkLogger
.warn("build", "PcdNvStoreDefaultValueBuffer should be defined as PcdsDynamicExVpd in dsc file since the DefaultStores is enabled for this platform.\n%s" %self
.Platform
.MetaFile
.Path
)
1410 PlatformPcds
= sorted(self
._PlatformPcds
.keys())
1412 # Add VPD type PCD into VpdFile and determine whether the VPD PCD need to be fixed up.
1415 for PcdKey
in PlatformPcds
:
1416 Pcd
= self
._PlatformPcds
[PcdKey
]
1417 if Pcd
.Type
in [TAB_PCDS_DYNAMIC_VPD
, TAB_PCDS_DYNAMIC_EX_VPD
] and \
1418 PcdKey
in VpdPcdDict
:
1419 Pcd
= VpdPcdDict
[PcdKey
]
1421 DefaultSku
= Pcd
.SkuInfoList
.get(TAB_DEFAULT
)
1423 PcdValue
= DefaultSku
.DefaultValue
1424 if PcdValue
not in SkuValueMap
:
1425 SkuValueMap
[PcdValue
] = []
1426 VpdFile
.Add(Pcd
, TAB_DEFAULT
, DefaultSku
.VpdOffset
)
1427 SkuValueMap
[PcdValue
].append(DefaultSku
)
1429 for (SkuName
, Sku
) in Pcd
.SkuInfoList
.items():
1430 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1431 PcdValue
= Sku
.DefaultValue
1433 PcdValue
= Pcd
.DefaultValue
1434 if Sku
.VpdOffset
!= '*':
1435 if PcdValue
.startswith("{"):
1437 elif PcdValue
.startswith("L"):
1442 VpdOffset
= int(Sku
.VpdOffset
)
1445 VpdOffset
= int(Sku
.VpdOffset
, 16)
1447 EdkLogger
.error("build", FORMAT_INVALID
, "Invalid offset value %s for PCD %s.%s." % (Sku
.VpdOffset
, Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
))
1448 if VpdOffset
% Alignment
!= 0:
1449 if PcdValue
.startswith("{"):
1450 EdkLogger
.warn("build", "The offset value of PCD %s.%s is not 8-byte aligned!" %(Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
), File
=self
.MetaFile
)
1452 EdkLogger
.error("build", FORMAT_INVALID
, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
, Alignment
))
1453 if PcdValue
not in SkuValueMap
:
1454 SkuValueMap
[PcdValue
] = []
1455 VpdFile
.Add(Pcd
, SkuName
, Sku
.VpdOffset
)
1456 SkuValueMap
[PcdValue
].append(Sku
)
1457 # if the offset of a VPD is *, then it need to be fixed up by third party tool.
1458 if not NeedProcessVpdMapFile
and Sku
.VpdOffset
== "*":
1459 NeedProcessVpdMapFile
= True
1460 if self
.Platform
.VpdToolGuid
is None or self
.Platform
.VpdToolGuid
== '':
1461 EdkLogger
.error("Build", FILE_NOT_FOUND
, \
1462 "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.")
1464 VpdSkuMap
[PcdKey
] = SkuValueMap
1466 # Fix the PCDs define in VPD PCD section that never referenced by module.
1467 # An example is PCD for signature usage.
1469 for DscPcd
in PlatformPcds
:
1470 DscPcdEntry
= self
._PlatformPcds
[DscPcd
]
1471 if DscPcdEntry
.Type
in [TAB_PCDS_DYNAMIC_VPD
, TAB_PCDS_DYNAMIC_EX_VPD
]:
1472 if not (self
.Platform
.VpdToolGuid
is None or self
.Platform
.VpdToolGuid
== ''):
1474 for VpdPcd
in VpdFile
._VpdArray
:
1475 # This PCD has been referenced by module
1476 if (VpdPcd
.TokenSpaceGuidCName
== DscPcdEntry
.TokenSpaceGuidCName
) and \
1477 (VpdPcd
.TokenCName
== DscPcdEntry
.TokenCName
):
1480 # Not found, it should be signature
1482 # just pick the a value to determine whether is unicode string type
1484 SkuObjList
= DscPcdEntry
.SkuInfoList
.items()
1485 DefaultSku
= DscPcdEntry
.SkuInfoList
.get(TAB_DEFAULT
)
1487 defaultindex
= SkuObjList
.index((TAB_DEFAULT
, DefaultSku
))
1488 SkuObjList
[0], SkuObjList
[defaultindex
] = SkuObjList
[defaultindex
], SkuObjList
[0]
1489 for (SkuName
, Sku
) in SkuObjList
:
1490 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1492 # Need to iterate DEC pcd information to get the value & datumtype
1493 for eachDec
in self
.PackageList
:
1494 for DecPcd
in eachDec
.Pcds
:
1495 DecPcdEntry
= eachDec
.Pcds
[DecPcd
]
1496 if (DecPcdEntry
.TokenSpaceGuidCName
== DscPcdEntry
.TokenSpaceGuidCName
) and \
1497 (DecPcdEntry
.TokenCName
== DscPcdEntry
.TokenCName
):
1498 # Print warning message to let the developer make a determine.
1499 EdkLogger
.warn("build", "Unreferenced vpd pcd used!",
1500 File
=self
.MetaFile
, \
1501 ExtraData
= "PCD: %s.%s used in the DSC file %s is unreferenced." \
1502 %(DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
, self
.Platform
.MetaFile
.Path
))
1504 DscPcdEntry
.DatumType
= DecPcdEntry
.DatumType
1505 DscPcdEntry
.DefaultValue
= DecPcdEntry
.DefaultValue
1506 DscPcdEntry
.TokenValue
= DecPcdEntry
.TokenValue
1507 DscPcdEntry
.TokenSpaceGuidValue
= eachDec
.Guids
[DecPcdEntry
.TokenSpaceGuidCName
]
1508 # Only fix the value while no value provided in DSC file.
1509 if not Sku
.DefaultValue
:
1510 DscPcdEntry
.SkuInfoList
[DscPcdEntry
.SkuInfoList
.keys()[0]].DefaultValue
= DecPcdEntry
.DefaultValue
1512 if DscPcdEntry
not in self
._DynamicPcdList
:
1513 self
._DynamicPcdList
.append(DscPcdEntry
)
1514 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1515 PcdValue
= Sku
.DefaultValue
1517 PcdValue
= DscPcdEntry
.DefaultValue
1518 if Sku
.VpdOffset
!= '*':
1519 if PcdValue
.startswith("{"):
1521 elif PcdValue
.startswith("L"):
1526 VpdOffset
= int(Sku
.VpdOffset
)
1529 VpdOffset
= int(Sku
.VpdOffset
, 16)
1531 EdkLogger
.error("build", FORMAT_INVALID
, "Invalid offset value %s for PCD %s.%s." % (Sku
.VpdOffset
, DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
))
1532 if VpdOffset
% Alignment
!= 0:
1533 if PcdValue
.startswith("{"):
1534 EdkLogger
.warn("build", "The offset value of PCD %s.%s is not 8-byte aligned!" %(DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
), File
=self
.MetaFile
)
1536 EdkLogger
.error("build", FORMAT_INVALID
, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
, Alignment
))
1537 if PcdValue
not in SkuValueMap
:
1538 SkuValueMap
[PcdValue
] = []
1539 VpdFile
.Add(DscPcdEntry
, SkuName
, Sku
.VpdOffset
)
1540 SkuValueMap
[PcdValue
].append(Sku
)
1541 if not NeedProcessVpdMapFile
and Sku
.VpdOffset
== "*":
1542 NeedProcessVpdMapFile
= True
1543 if DscPcdEntry
.DatumType
== TAB_VOID
and PcdValue
.startswith("L"):
1544 UnicodePcdArray
.add(DscPcdEntry
)
1545 elif len(Sku
.VariableName
) > 0:
1546 HiiPcdArray
.add(DscPcdEntry
)
1548 OtherPcdArray
.add(DscPcdEntry
)
1550 # if the offset of a VPD is *, then it need to be fixed up by third party tool.
1551 VpdSkuMap
[DscPcd
] = SkuValueMap
1552 if (self
.Platform
.FlashDefinition
is None or self
.Platform
.FlashDefinition
== '') and \
1553 VpdFile
.GetCount() != 0:
1554 EdkLogger
.error("build", ATTRIBUTE_NOT_AVAILABLE
,
1555 "Fail to get FLASH_DEFINITION definition in DSC file %s which is required when DSC contains VPD PCD." % str(self
.Platform
.MetaFile
))
1557 if VpdFile
.GetCount() != 0:
1559 self
.FixVpdOffset(VpdFile
)
1561 self
.FixVpdOffset(self
.UpdateNVStoreMaxSize(VpdFile
))
1563 # Process VPD map file generated by third party BPDG tool
1564 if NeedProcessVpdMapFile
:
1565 VpdMapFilePath
= os
.path
.join(self
.BuildDir
, TAB_FV_DIRECTORY
, "%s.map" % self
.Platform
.VpdToolGuid
)
1566 if os
.path
.exists(VpdMapFilePath
):
1567 VpdFile
.Read(VpdMapFilePath
)
1570 for pcd
in VpdSkuMap
:
1571 vpdinfo
= VpdFile
.GetVpdInfo(pcd
)
1573 # just pick the a value to determine whether is unicode string type
1575 for pcdvalue
in VpdSkuMap
[pcd
]:
1576 for sku
in VpdSkuMap
[pcd
][pcdvalue
]:
1577 for item
in vpdinfo
:
1578 if item
[2] == pcdvalue
:
1579 sku
.VpdOffset
= item
[1]
1581 EdkLogger
.error("build", FILE_READ_FAILURE
, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath
)
1583 # Delete the DynamicPcdList At the last time enter into this function
1584 for Pcd
in self
._DynamicPcdList
:
1585 # just pick the a value to determine whether is unicode string type
1586 Sku
= Pcd
.SkuInfoList
.values()[0]
1587 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1589 if Pcd
.DatumType
not in [TAB_UINT8
, TAB_UINT16
, TAB_UINT32
, TAB_UINT64
, TAB_VOID
, "BOOLEAN"]:
1590 Pcd
.DatumType
= TAB_VOID
1592 PcdValue
= Sku
.DefaultValue
1593 if Pcd
.DatumType
== TAB_VOID
and PcdValue
.startswith("L"):
1594 # if found PCD which datum value is unicode string the insert to left size of UnicodeIndex
1595 UnicodePcdArray
.add(Pcd
)
1596 elif len(Sku
.VariableName
) > 0:
1597 # if found HII type PCD then insert to right of UnicodeIndex
1598 HiiPcdArray
.add(Pcd
)
1600 OtherPcdArray
.add(Pcd
)
1601 del self
._DynamicPcdList
[:]
1602 self
._DynamicPcdList
.extend(list(UnicodePcdArray
))
1603 self
._DynamicPcdList
.extend(list(HiiPcdArray
))
1604 self
._DynamicPcdList
.extend(list(OtherPcdArray
))
1605 allskuset
= [(SkuName
, Sku
.SkuId
) for pcd
in self
._DynamicPcdList
for (SkuName
, Sku
) in pcd
.SkuInfoList
.items()]
1606 for pcd
in self
._DynamicPcdList
:
1607 if len(pcd
.SkuInfoList
) == 1:
1608 for (SkuName
, SkuId
) in allskuset
:
1609 if type(SkuId
) in (str, unicode) and eval(SkuId
) == 0 or SkuId
== 0:
1611 pcd
.SkuInfoList
[SkuName
] = copy
.deepcopy(pcd
.SkuInfoList
[TAB_DEFAULT
])
1612 pcd
.SkuInfoList
[SkuName
].SkuId
= SkuId
1613 pcd
.SkuInfoList
[SkuName
].SkuIdName
= SkuName
1614 self
.AllPcdList
= self
._NonDynamicPcdList
+ self
._DynamicPcdList
1616 def FixVpdOffset(self
, VpdFile
):
1617 FvPath
= os
.path
.join(self
.BuildDir
, TAB_FV_DIRECTORY
)
1618 if not os
.path
.exists(FvPath
):
1622 EdkLogger
.error("build", FILE_WRITE_FAILURE
, "Fail to create FV folder under %s" % self
.BuildDir
)
1624 VpdFilePath
= os
.path
.join(FvPath
, "%s.txt" % self
.Platform
.VpdToolGuid
)
1626 if VpdFile
.Write(VpdFilePath
):
1627 # retrieve BPDG tool's path from tool_def.txt according to VPD_TOOL_GUID defined in DSC file.
1629 for ToolDef
in self
.ToolDefinition
.values():
1630 if TAB_GUID
in ToolDef
and ToolDef
[TAB_GUID
] == self
.Platform
.VpdToolGuid
:
1631 if "PATH" not in ToolDef
:
1632 EdkLogger
.error("build", ATTRIBUTE_NOT_AVAILABLE
, "PATH attribute was not provided for BPDG guid tool %s in tools_def.txt" % self
.Platform
.VpdToolGuid
)
1633 BPDGToolName
= ToolDef
["PATH"]
1635 # Call third party GUID BPDG tool.
1636 if BPDGToolName
is not None:
1637 VpdInfoFile
.CallExtenalBPDGTool(BPDGToolName
, VpdFilePath
)
1639 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.")
1641 ## Return the platform build data object
1644 return self
.BuildDatabase
[self
.MetaFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1646 ## Return platform name
1649 return self
.Platform
.PlatformName
1651 ## Return the meta file GUID
1654 return self
.Platform
.Guid
1656 ## Return the platform version
1659 return self
.Platform
.Version
1661 ## Return the FDF file name
1664 if self
.Workspace
.FdfFile
:
1665 RetVal
= mws
.join(self
.WorkspaceDir
, self
.Workspace
.FdfFile
)
1670 ## Return the build output directory platform specifies
1672 def OutputDir(self
):
1673 return self
.Platform
.OutputDirectory
1675 ## Return the directory to store all intermediate and final files built
1678 if os
.path
.isabs(self
.OutputDir
):
1679 GlobalData
.gBuildDirectory
= RetVal
= path
.join(
1680 path
.abspath(self
.OutputDir
),
1681 self
.BuildTarget
+ "_" + self
.ToolChain
,
1684 GlobalData
.gBuildDirectory
= RetVal
= path
.join(
1687 self
.BuildTarget
+ "_" + self
.ToolChain
,
1691 ## Return directory of platform makefile
1693 # @retval string Makefile directory
1696 def MakeFileDir(self
):
1697 return path
.join(self
.BuildDir
, self
.Arch
)
1699 ## Return build command string
1701 # @retval string Build command string
1704 def BuildCommand(self
):
1706 if "MAKE" in self
.ToolDefinition
and "PATH" in self
.ToolDefinition
["MAKE"]:
1707 RetVal
+= SplitOption(self
.ToolDefinition
["MAKE"]["PATH"])
1708 if "FLAGS" in self
.ToolDefinition
["MAKE"]:
1709 NewOption
= self
.ToolDefinition
["MAKE"]["FLAGS"].strip()
1711 RetVal
+= SplitOption(NewOption
)
1712 if "MAKE" in self
.EdkIIBuildOption
:
1713 if "FLAGS" in self
.EdkIIBuildOption
["MAKE"]:
1714 Flags
= self
.EdkIIBuildOption
["MAKE"]["FLAGS"]
1715 if Flags
.startswith('='):
1716 RetVal
= [RetVal
[0]] + [Flags
[1:]]
1718 RetVal
.append(Flags
)
1721 ## Get tool chain definition
1723 # Get each tool defition for given tool chain from tools_def.txt and platform
1726 def ToolDefinition(self
):
1727 ToolDefinition
= self
.Workspace
.ToolDef
.ToolsDefTxtDictionary
1728 if TAB_TOD_DEFINES_COMMAND_TYPE
not in self
.Workspace
.ToolDef
.ToolsDefTxtDatabase
:
1729 EdkLogger
.error('build', RESOURCE_NOT_AVAILABLE
, "No tools found in configuration",
1730 ExtraData
="[%s]" % self
.MetaFile
)
1733 for Def
in ToolDefinition
:
1734 Target
, Tag
, Arch
, Tool
, Attr
= Def
.split("_")
1735 if Target
!= self
.BuildTarget
or Tag
!= self
.ToolChain
or Arch
!= self
.Arch
:
1738 Value
= ToolDefinition
[Def
]
1739 # don't record the DLL
1741 DllPathList
.add(Value
)
1744 if Tool
not in RetVal
:
1746 RetVal
[Tool
][Attr
] = Value
1749 if GlobalData
.gOptions
.SilentMode
and "MAKE" in RetVal
:
1750 if "FLAGS" not in RetVal
["MAKE"]:
1751 RetVal
["MAKE"]["FLAGS"] = ""
1752 RetVal
["MAKE"]["FLAGS"] += " -s"
1755 for Attr
in RetVal
[Tool
]:
1756 Value
= RetVal
[Tool
][Attr
]
1757 if Tool
in self
._BuildOptionWithToolDef
(RetVal
) and Attr
in self
._BuildOptionWithToolDef
(RetVal
)[Tool
]:
1758 # check if override is indicated
1759 if self
._BuildOptionWithToolDef
(RetVal
)[Tool
][Attr
].startswith('='):
1760 Value
= self
._BuildOptionWithToolDef
(RetVal
)[Tool
][Attr
][1:]
1763 Value
+= " " + self
._BuildOptionWithToolDef
(RetVal
)[Tool
][Attr
]
1765 Value
= self
._BuildOptionWithToolDef
(RetVal
)[Tool
][Attr
]
1768 # Don't put MAKE definition in the file
1770 ToolsDef
+= "%s = %s\n" % (Tool
, Value
)
1772 # Don't put MAKE definition in the file
1777 ToolsDef
+= "%s_%s = %s\n" % (Tool
, Attr
, Value
)
1780 SaveFileOnChange(self
.ToolDefinitionFile
, ToolsDef
)
1781 for DllPath
in DllPathList
:
1782 os
.environ
["PATH"] = DllPath
+ os
.pathsep
+ os
.environ
["PATH"]
1783 os
.environ
["MAKE_FLAGS"] = MakeFlags
1787 ## Return the paths of tools
1789 def ToolDefinitionFile(self
):
1790 return os
.path
.join(self
.MakeFileDir
, "TOOLS_DEF." + self
.Arch
)
1792 ## Retrieve the toolchain family of given toolchain tag. Default to 'MSFT'.
1794 def ToolChainFamily(self
):
1795 ToolDefinition
= self
.Workspace
.ToolDef
.ToolsDefTxtDatabase
1796 if TAB_TOD_DEFINES_FAMILY
not in ToolDefinition \
1797 or self
.ToolChain
not in ToolDefinition
[TAB_TOD_DEFINES_FAMILY
] \
1798 or not ToolDefinition
[TAB_TOD_DEFINES_FAMILY
][self
.ToolChain
]:
1799 EdkLogger
.verbose("No tool chain family found in configuration for %s. Default to MSFT." \
1801 RetVal
= TAB_COMPILER_MSFT
1803 RetVal
= ToolDefinition
[TAB_TOD_DEFINES_FAMILY
][self
.ToolChain
]
1807 def BuildRuleFamily(self
):
1808 ToolDefinition
= self
.Workspace
.ToolDef
.ToolsDefTxtDatabase
1809 if TAB_TOD_DEFINES_BUILDRULEFAMILY
not in ToolDefinition \
1810 or self
.ToolChain
not in ToolDefinition
[TAB_TOD_DEFINES_BUILDRULEFAMILY
] \
1811 or not ToolDefinition
[TAB_TOD_DEFINES_BUILDRULEFAMILY
][self
.ToolChain
]:
1812 EdkLogger
.verbose("No tool chain family found in configuration for %s. Default to MSFT." \
1814 return TAB_COMPILER_MSFT
1816 return ToolDefinition
[TAB_TOD_DEFINES_BUILDRULEFAMILY
][self
.ToolChain
]
1818 ## Return the build options specific for all modules in this platform
1820 def BuildOption(self
):
1821 return self
._ExpandBuildOption
(self
.Platform
.BuildOptions
)
1823 def _BuildOptionWithToolDef(self
, ToolDef
):
1824 return self
._ExpandBuildOption
(self
.Platform
.BuildOptions
, ToolDef
=ToolDef
)
1826 ## Return the build options specific for EDK modules in this platform
1828 def EdkBuildOption(self
):
1829 return self
._ExpandBuildOption
(self
.Platform
.BuildOptions
, EDK_NAME
)
1831 ## Return the build options specific for EDKII modules in this platform
1833 def EdkIIBuildOption(self
):
1834 return self
._ExpandBuildOption
(self
.Platform
.BuildOptions
, EDKII_NAME
)
1836 ## Parse build_rule.txt in Conf Directory.
1838 # @retval BuildRule object
1841 def BuildRule(self
):
1842 BuildRuleFile
= None
1843 if TAB_TAT_DEFINES_BUILD_RULE_CONF
in self
.Workspace
.TargetTxt
.TargetTxtDictionary
:
1844 BuildRuleFile
= self
.Workspace
.TargetTxt
.TargetTxtDictionary
[TAB_TAT_DEFINES_BUILD_RULE_CONF
]
1845 if not BuildRuleFile
:
1846 BuildRuleFile
= gDefaultBuildRuleFile
1847 RetVal
= BuildRule(BuildRuleFile
)
1848 if RetVal
._FileVersion
== "":
1849 RetVal
._FileVersion
= AutoGenReqBuildRuleVerNum
1851 if RetVal
._FileVersion
< AutoGenReqBuildRuleVerNum
:
1852 # If Build Rule's version is less than the version number required by the tools, halting the build.
1853 EdkLogger
.error("build", AUTOGEN_ERROR
,
1854 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])"\
1855 % (RetVal
._FileVersion
, AutoGenReqBuildRuleVerNum
))
1858 ## Summarize the packages used by modules in this platform
1860 def PackageList(self
):
1862 for La
in self
.LibraryAutoGenList
:
1863 RetVal
.update(La
.DependentPackageList
)
1864 for Ma
in self
.ModuleAutoGenList
:
1865 RetVal
.update(Ma
.DependentPackageList
)
1866 #Collect package set information from INF of FDF
1867 for ModuleFile
in self
._AsBuildModuleList
:
1868 if ModuleFile
in self
.Platform
.Modules
:
1870 ModuleData
= self
.BuildDatabase
[ModuleFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1871 RetVal
.update(ModuleData
.Packages
)
1875 def NonDynamicPcdDict(self
):
1876 return {(Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
):Pcd
for Pcd
in self
.NonDynamicPcdList
}
1878 ## Get list of non-dynamic PCDs
1880 def NonDynamicPcdList(self
):
1881 self
.CollectPlatformDynamicPcds()
1882 return self
._NonDynamicPcdList
1884 ## Get list of dynamic PCDs
1886 def DynamicPcdList(self
):
1887 self
.CollectPlatformDynamicPcds()
1888 return self
._DynamicPcdList
1890 ## Generate Token Number for all PCD
1892 def PcdTokenNumber(self
):
1893 RetVal
= OrderedDict()
1896 # Make the Dynamic and DynamicEx PCD use within different TokenNumber area.
1900 # TokenNumber 0 ~ 10
1902 # TokeNumber 11 ~ 20
1904 for Pcd
in self
.DynamicPcdList
:
1905 if Pcd
.Phase
== "PEI" and Pcd
.Type
in PCD_DYNAMIC_TYPE_SET
:
1906 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
1907 RetVal
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
1910 for Pcd
in self
.DynamicPcdList
:
1911 if Pcd
.Phase
== "PEI" and Pcd
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
1912 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
1913 RetVal
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
1916 for Pcd
in self
.DynamicPcdList
:
1917 if Pcd
.Phase
== "DXE" and Pcd
.Type
in PCD_DYNAMIC_TYPE_SET
:
1918 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
1919 RetVal
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
1922 for Pcd
in self
.DynamicPcdList
:
1923 if Pcd
.Phase
== "DXE" and Pcd
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
1924 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
1925 RetVal
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
1928 for Pcd
in self
.NonDynamicPcdList
:
1929 RetVal
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
1935 for ModuleFile
in self
.Platform
.Modules
:
1944 self
.Platform
.Modules
[ModuleFile
].M
= Ma
1945 return [x
.M
for x
in self
.Platform
.Modules
.values()]
1947 ## Summarize ModuleAutoGen objects of all modules to be built for this platform
1949 def ModuleAutoGenList(self
):
1951 for Ma
in self
._MaList
:
1952 if Ma
not in RetVal
:
1956 ## Summarize ModuleAutoGen objects of all libraries to be built for this platform
1958 def LibraryAutoGenList(self
):
1960 for Ma
in self
._MaList
:
1961 for La
in Ma
.LibraryAutoGenList
:
1962 if La
not in RetVal
:
1964 if Ma
not in La
.ReferenceModules
:
1965 La
.ReferenceModules
.append(Ma
)
1968 ## Test if a module is supported by the platform
1970 # An error will be raised directly if the module or its arch is not supported
1971 # by the platform or current configuration
1973 def ValidModule(self
, Module
):
1974 return Module
in self
.Platform
.Modules
or Module
in self
.Platform
.LibraryInstances \
1975 or Module
in self
._AsBuildModuleList
1977 ## Resolve the library classes in a module to library instances
1979 # This method will not only resolve library classes but also sort the library
1980 # instances according to the dependency-ship.
1982 # @param Module The module from which the library classes will be resolved
1984 # @retval library_list List of library instances sorted
1986 def ApplyLibraryInstance(self
, Module
):
1987 # Cover the case that the binary INF file is list in the FDF file but not DSC file, return empty list directly
1988 if str(Module
) not in self
.Platform
.Modules
:
1991 return GetModuleLibInstances(Module
,
2000 ## Override PCD setting (type, value, ...)
2002 # @param ToPcd The PCD to be overrided
2003 # @param FromPcd The PCD overrideing from
2005 def _OverridePcd(self
, ToPcd
, FromPcd
, Module
="", Msg
="", Library
=""):
2007 # in case there's PCDs coming from FDF file, which have no type given.
2008 # at this point, ToPcd.Type has the type found from dependent
2011 TokenCName
= ToPcd
.TokenCName
2012 for PcdItem
in GlobalData
.MixedPcd
:
2013 if (ToPcd
.TokenCName
, ToPcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
2014 TokenCName
= PcdItem
[0]
2016 if FromPcd
is not None:
2017 if ToPcd
.Pending
and FromPcd
.Type
:
2018 ToPcd
.Type
= FromPcd
.Type
2019 elif ToPcd
.Type
and FromPcd
.Type\
2020 and ToPcd
.Type
!= FromPcd
.Type
and ToPcd
.Type
in FromPcd
.Type
:
2021 if ToPcd
.Type
.strip() == TAB_PCDS_DYNAMIC_EX
:
2022 ToPcd
.Type
= FromPcd
.Type
2023 elif ToPcd
.Type
and FromPcd
.Type \
2024 and ToPcd
.Type
!= FromPcd
.Type
:
2026 Module
= str(Module
) + " 's library file (" + str(Library
) + ")"
2027 EdkLogger
.error("build", OPTION_CONFLICT
, "Mismatched PCD type",
2028 ExtraData
="%s.%s is used as [%s] in module %s, but as [%s] in %s."\
2029 % (ToPcd
.TokenSpaceGuidCName
, TokenCName
,
2030 ToPcd
.Type
, Module
, FromPcd
.Type
, Msg
),
2033 if FromPcd
.MaxDatumSize
:
2034 ToPcd
.MaxDatumSize
= FromPcd
.MaxDatumSize
2035 ToPcd
.MaxSizeUserSet
= FromPcd
.MaxDatumSize
2036 if FromPcd
.DefaultValue
:
2037 ToPcd
.DefaultValue
= FromPcd
.DefaultValue
2038 if FromPcd
.TokenValue
:
2039 ToPcd
.TokenValue
= FromPcd
.TokenValue
2040 if FromPcd
.DatumType
:
2041 ToPcd
.DatumType
= FromPcd
.DatumType
2042 if FromPcd
.SkuInfoList
:
2043 ToPcd
.SkuInfoList
= FromPcd
.SkuInfoList
2044 if FromPcd
.UserDefinedDefaultStoresFlag
:
2045 ToPcd
.UserDefinedDefaultStoresFlag
= FromPcd
.UserDefinedDefaultStoresFlag
2046 # Add Flexible PCD format parse
2047 if ToPcd
.DefaultValue
:
2049 ToPcd
.DefaultValue
= ValueExpressionEx(ToPcd
.DefaultValue
, ToPcd
.DatumType
, self
.Workspace
._GuidDict
)(True)
2050 except BadExpression
as Value
:
2051 EdkLogger
.error('Parser', FORMAT_INVALID
, 'PCD [%s.%s] Value "%s", %s' %(ToPcd
.TokenSpaceGuidCName
, ToPcd
.TokenCName
, ToPcd
.DefaultValue
, Value
),
2054 # check the validation of datum
2055 IsValid
, Cause
= CheckPcdDatum(ToPcd
.DatumType
, ToPcd
.DefaultValue
)
2057 EdkLogger
.error('build', FORMAT_INVALID
, Cause
, File
=self
.MetaFile
,
2058 ExtraData
="%s.%s" % (ToPcd
.TokenSpaceGuidCName
, TokenCName
))
2059 ToPcd
.validateranges
= FromPcd
.validateranges
2060 ToPcd
.validlists
= FromPcd
.validlists
2061 ToPcd
.expressions
= FromPcd
.expressions
2062 ToPcd
.CustomAttribute
= FromPcd
.CustomAttribute
2064 if FromPcd
is not None and ToPcd
.DatumType
== TAB_VOID
and not ToPcd
.MaxDatumSize
:
2065 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "No MaxDatumSize specified for PCD %s.%s" \
2066 % (ToPcd
.TokenSpaceGuidCName
, TokenCName
))
2067 Value
= ToPcd
.DefaultValue
2069 ToPcd
.MaxDatumSize
= '1'
2070 elif Value
[0] == 'L':
2071 ToPcd
.MaxDatumSize
= str((len(Value
) - 2) * 2)
2072 elif Value
[0] == '{':
2073 ToPcd
.MaxDatumSize
= str(len(Value
.split(',')))
2075 ToPcd
.MaxDatumSize
= str(len(Value
) - 1)
2077 # apply default SKU for dynamic PCDS if specified one is not available
2078 if (ToPcd
.Type
in PCD_DYNAMIC_TYPE_SET
or ToPcd
.Type
in PCD_DYNAMIC_EX_TYPE_SET
) \
2079 and not ToPcd
.SkuInfoList
:
2080 if self
.Platform
.SkuName
in self
.Platform
.SkuIds
:
2081 SkuName
= self
.Platform
.SkuName
2083 SkuName
= TAB_DEFAULT
2084 ToPcd
.SkuInfoList
= {
2085 SkuName
: SkuInfoClass(SkuName
, self
.Platform
.SkuIds
[SkuName
][0], '', '', '', '', '', ToPcd
.DefaultValue
)
2088 ## Apply PCD setting defined platform to a module
2090 # @param Module The module from which the PCD setting will be overrided
2092 # @retval PCD_list The list PCDs with settings from platform
2094 def ApplyPcdSetting(self
, Module
, Pcds
, Library
=""):
2095 # for each PCD in module
2096 for Name
, Guid
in Pcds
:
2097 PcdInModule
= Pcds
[Name
, Guid
]
2098 # find out the PCD setting in platform
2099 if (Name
, Guid
) in self
.Platform
.Pcds
:
2100 PcdInPlatform
= self
.Platform
.Pcds
[Name
, Guid
]
2102 PcdInPlatform
= None
2103 # then override the settings if any
2104 self
._OverridePcd
(PcdInModule
, PcdInPlatform
, Module
, Msg
="DSC PCD sections", Library
=Library
)
2105 # resolve the VariableGuid value
2106 for SkuId
in PcdInModule
.SkuInfoList
:
2107 Sku
= PcdInModule
.SkuInfoList
[SkuId
]
2108 if Sku
.VariableGuid
== '': continue
2109 Sku
.VariableGuidValue
= GuidValue(Sku
.VariableGuid
, self
.PackageList
, self
.MetaFile
.Path
)
2110 if Sku
.VariableGuidValue
is None:
2111 PackageList
= "\n\t".join(str(P
) for P
in self
.PackageList
)
2114 RESOURCE_NOT_AVAILABLE
,
2115 "Value of GUID [%s] is not found in" % Sku
.VariableGuid
,
2116 ExtraData
=PackageList
+ "\n\t(used with %s.%s from module %s)" \
2117 % (Guid
, Name
, str(Module
)),
2121 # override PCD settings with module specific setting
2122 if Module
in self
.Platform
.Modules
:
2123 PlatformModule
= self
.Platform
.Modules
[str(Module
)]
2124 for Key
in PlatformModule
.Pcds
:
2125 if GlobalData
.BuildOptionPcd
:
2126 for pcd
in GlobalData
.BuildOptionPcd
:
2127 (TokenSpaceGuidCName
, TokenCName
, FieldName
, pcdvalue
, _
) = pcd
2128 if (TokenCName
, TokenSpaceGuidCName
) == Key
and FieldName
=="":
2129 PlatformModule
.Pcds
[Key
].DefaultValue
= pcdvalue
2130 PlatformModule
.Pcds
[Key
].PcdValueFromComm
= pcdvalue
2136 elif Key
in GlobalData
.MixedPcd
:
2137 for PcdItem
in GlobalData
.MixedPcd
[Key
]:
2139 ToPcd
= Pcds
[PcdItem
]
2143 self
._OverridePcd
(ToPcd
, PlatformModule
.Pcds
[Key
], Module
, Msg
="DSC Components Module scoped PCD section", Library
=Library
)
2144 # use PCD value to calculate the MaxDatumSize when it is not specified
2145 for Name
, Guid
in Pcds
:
2146 Pcd
= Pcds
[Name
, Guid
]
2147 if Pcd
.DatumType
== TAB_VOID
and not Pcd
.MaxDatumSize
:
2148 Pcd
.MaxSizeUserSet
= None
2149 Value
= Pcd
.DefaultValue
2151 Pcd
.MaxDatumSize
= '1'
2152 elif Value
[0] == 'L':
2153 Pcd
.MaxDatumSize
= str((len(Value
) - 2) * 2)
2154 elif Value
[0] == '{':
2155 Pcd
.MaxDatumSize
= str(len(Value
.split(',')))
2157 Pcd
.MaxDatumSize
= str(len(Value
) - 1)
2158 return Pcds
.values()
2160 ## Resolve library names to library modules
2162 # (for Edk.x modules)
2164 # @param Module The module from which the library names will be resolved
2166 # @retval library_list The list of library modules
2168 def ResolveLibraryReference(self
, Module
):
2169 EdkLogger
.verbose("")
2170 EdkLogger
.verbose("Library instances of module [%s] [%s]:" % (str(Module
), self
.Arch
))
2171 LibraryConsumerList
= [Module
]
2173 # "CompilerStub" is a must for Edk modules
2174 if Module
.Libraries
:
2175 Module
.Libraries
.append("CompilerStub")
2177 while len(LibraryConsumerList
) > 0:
2178 M
= LibraryConsumerList
.pop()
2179 for LibraryName
in M
.Libraries
:
2180 Library
= self
.Platform
.LibraryClasses
[LibraryName
, ':dummy:']
2182 for Key
in self
.Platform
.LibraryClasses
.data
:
2183 if LibraryName
.upper() == Key
.upper():
2184 Library
= self
.Platform
.LibraryClasses
[Key
, ':dummy:']
2187 EdkLogger
.warn("build", "Library [%s] is not found" % LibraryName
, File
=str(M
),
2188 ExtraData
="\t%s [%s]" % (str(Module
), self
.Arch
))
2191 if Library
not in LibraryList
:
2192 LibraryList
.append(Library
)
2193 LibraryConsumerList
.append(Library
)
2194 EdkLogger
.verbose("\t" + LibraryName
+ " : " + str(Library
) + ' ' + str(type(Library
)))
2197 ## Calculate the priority value of the build option
2199 # @param Key Build option definition contain: TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
2201 # @retval Value Priority value based on the priority list.
2203 def CalculatePriorityValue(self
, Key
):
2204 Target
, ToolChain
, Arch
, CommandType
, Attr
= Key
.split('_')
2205 PriorityValue
= 0x11111
2207 PriorityValue
&= 0x01111
2208 if ToolChain
== "*":
2209 PriorityValue
&= 0x10111
2211 PriorityValue
&= 0x11011
2212 if CommandType
== "*":
2213 PriorityValue
&= 0x11101
2215 PriorityValue
&= 0x11110
2217 return self
.PrioList
["0x%0.5x" % PriorityValue
]
2220 ## Expand * in build option key
2222 # @param Options Options to be expanded
2223 # @param ToolDef Use specified ToolDef instead of full version.
2224 # This is needed during initialization to prevent
2225 # infinite recursion betweeh BuildOptions,
2226 # ToolDefinition, and this function.
2228 # @retval options Options expanded
2230 def _ExpandBuildOption(self
, Options
, ModuleStyle
=None, ToolDef
=None):
2232 ToolDef
= self
.ToolDefinition
2239 # Construct a list contain the build options which need override.
2243 # Key[0] -- tool family
2244 # Key[1] -- TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
2246 if (Key
[0] == self
.BuildRuleFamily
and
2247 (ModuleStyle
is None or len(Key
) < 3 or (len(Key
) > 2 and Key
[2] == ModuleStyle
))):
2248 Target
, ToolChain
, Arch
, CommandType
, Attr
= Key
[1].split('_')
2249 if (Target
== self
.BuildTarget
or Target
== "*") and\
2250 (ToolChain
== self
.ToolChain
or ToolChain
== "*") and\
2251 (Arch
== self
.Arch
or Arch
== "*") and\
2252 Options
[Key
].startswith("="):
2254 if OverrideList
.get(Key
[1]) is not None:
2255 OverrideList
.pop(Key
[1])
2256 OverrideList
[Key
[1]] = Options
[Key
]
2259 # Use the highest priority value.
2261 if (len(OverrideList
) >= 2):
2262 KeyList
= OverrideList
.keys()
2263 for Index
in range(len(KeyList
)):
2264 NowKey
= KeyList
[Index
]
2265 Target1
, ToolChain1
, Arch1
, CommandType1
, Attr1
= NowKey
.split("_")
2266 for Index1
in range(len(KeyList
) - Index
- 1):
2267 NextKey
= KeyList
[Index1
+ Index
+ 1]
2269 # Compare two Key, if one is included by another, choose the higher priority one
2271 Target2
, ToolChain2
, Arch2
, CommandType2
, Attr2
= NextKey
.split("_")
2272 if (Target1
== Target2
or Target1
== "*" or Target2
== "*") and\
2273 (ToolChain1
== ToolChain2
or ToolChain1
== "*" or ToolChain2
== "*") and\
2274 (Arch1
== Arch2
or Arch1
== "*" or Arch2
== "*") and\
2275 (CommandType1
== CommandType2
or CommandType1
== "*" or CommandType2
== "*") and\
2276 (Attr1
== Attr2
or Attr1
== "*" or Attr2
== "*"):
2278 if self
.CalculatePriorityValue(NowKey
) > self
.CalculatePriorityValue(NextKey
):
2279 if Options
.get((self
.BuildRuleFamily
, NextKey
)) is not None:
2280 Options
.pop((self
.BuildRuleFamily
, NextKey
))
2282 if Options
.get((self
.BuildRuleFamily
, NowKey
)) is not None:
2283 Options
.pop((self
.BuildRuleFamily
, NowKey
))
2286 if ModuleStyle
is not None and len (Key
) > 2:
2287 # Check Module style is EDK or EDKII.
2288 # Only append build option for the matched style module.
2289 if ModuleStyle
== EDK_NAME
and Key
[2] != EDK_NAME
:
2291 elif ModuleStyle
== EDKII_NAME
and Key
[2] != EDKII_NAME
:
2294 Target
, Tag
, Arch
, Tool
, Attr
= Key
[1].split("_")
2295 # if tool chain family doesn't match, skip it
2296 if Tool
in ToolDef
and Family
!= "":
2297 FamilyIsNull
= False
2298 if ToolDef
[Tool
].get(TAB_TOD_DEFINES_BUILDRULEFAMILY
, "") != "":
2299 if Family
!= ToolDef
[Tool
][TAB_TOD_DEFINES_BUILDRULEFAMILY
]:
2301 elif Family
!= ToolDef
[Tool
][TAB_TOD_DEFINES_FAMILY
]:
2304 # expand any wildcard
2305 if Target
== "*" or Target
== self
.BuildTarget
:
2306 if Tag
== "*" or Tag
== self
.ToolChain
:
2307 if Arch
== "*" or Arch
== self
.Arch
:
2308 if Tool
not in BuildOptions
:
2309 BuildOptions
[Tool
] = {}
2310 if Attr
!= "FLAGS" or Attr
not in BuildOptions
[Tool
] or Options
[Key
].startswith('='):
2311 BuildOptions
[Tool
][Attr
] = Options
[Key
]
2313 # append options for the same tool except PATH
2315 BuildOptions
[Tool
][Attr
] += " " + Options
[Key
]
2317 BuildOptions
[Tool
][Attr
] = Options
[Key
]
2318 # Build Option Family has been checked, which need't to be checked again for family.
2319 if FamilyMatch
or FamilyIsNull
:
2323 if ModuleStyle
is not None and len (Key
) > 2:
2324 # Check Module style is EDK or EDKII.
2325 # Only append build option for the matched style module.
2326 if ModuleStyle
== EDK_NAME
and Key
[2] != EDK_NAME
:
2328 elif ModuleStyle
== EDKII_NAME
and Key
[2] != EDKII_NAME
:
2331 Target
, Tag
, Arch
, Tool
, Attr
= Key
[1].split("_")
2332 # if tool chain family doesn't match, skip it
2333 if Tool
not in ToolDef
or Family
== "":
2335 # option has been added before
2336 if Family
!= ToolDef
[Tool
][TAB_TOD_DEFINES_FAMILY
]:
2339 # expand any wildcard
2340 if Target
== "*" or Target
== self
.BuildTarget
:
2341 if Tag
== "*" or Tag
== self
.ToolChain
:
2342 if Arch
== "*" or Arch
== self
.Arch
:
2343 if Tool
not in BuildOptions
:
2344 BuildOptions
[Tool
] = {}
2345 if Attr
!= "FLAGS" or Attr
not in BuildOptions
[Tool
] or Options
[Key
].startswith('='):
2346 BuildOptions
[Tool
][Attr
] = Options
[Key
]
2348 # append options for the same tool except PATH
2350 BuildOptions
[Tool
][Attr
] += " " + Options
[Key
]
2352 BuildOptions
[Tool
][Attr
] = Options
[Key
]
2355 ## Append build options in platform to a module
2357 # @param Module The module to which the build options will be appened
2359 # @retval options The options appended with build options in platform
2361 def ApplyBuildOption(self
, Module
):
2362 # Get the different options for the different style module
2363 if Module
.AutoGenVersion
< 0x00010005:
2364 PlatformOptions
= self
.EdkBuildOption
2365 ModuleTypeOptions
= self
.Platform
.GetBuildOptionsByModuleType(EDK_NAME
, Module
.ModuleType
)
2367 PlatformOptions
= self
.EdkIIBuildOption
2368 ModuleTypeOptions
= self
.Platform
.GetBuildOptionsByModuleType(EDKII_NAME
, Module
.ModuleType
)
2369 ModuleTypeOptions
= self
._ExpandBuildOption
(ModuleTypeOptions
)
2370 ModuleOptions
= self
._ExpandBuildOption
(Module
.BuildOptions
)
2371 if Module
in self
.Platform
.Modules
:
2372 PlatformModule
= self
.Platform
.Modules
[str(Module
)]
2373 PlatformModuleOptions
= self
._ExpandBuildOption
(PlatformModule
.BuildOptions
)
2375 PlatformModuleOptions
= {}
2377 BuildRuleOrder
= None
2378 for Options
in [self
.ToolDefinition
, ModuleOptions
, PlatformOptions
, ModuleTypeOptions
, PlatformModuleOptions
]:
2379 for Tool
in Options
:
2380 for Attr
in Options
[Tool
]:
2381 if Attr
== TAB_TOD_DEFINES_BUILDRULEORDER
:
2382 BuildRuleOrder
= Options
[Tool
][Attr
]
2384 AllTools
= set(ModuleOptions
.keys() + PlatformOptions
.keys() +
2385 PlatformModuleOptions
.keys() + ModuleTypeOptions
.keys() +
2386 self
.ToolDefinition
.keys())
2387 BuildOptions
= defaultdict(lambda: defaultdict(str))
2388 for Tool
in AllTools
:
2389 for Options
in [self
.ToolDefinition
, ModuleOptions
, PlatformOptions
, ModuleTypeOptions
, PlatformModuleOptions
]:
2390 if Tool
not in Options
:
2392 for Attr
in Options
[Tool
]:
2394 # Do not generate it in Makefile
2396 if Attr
== TAB_TOD_DEFINES_BUILDRULEORDER
:
2398 Value
= Options
[Tool
][Attr
]
2399 # check if override is indicated
2400 if Value
.startswith('='):
2401 BuildOptions
[Tool
][Attr
] = mws
.handleWsMacro(Value
[1:])
2404 BuildOptions
[Tool
][Attr
] += " " + mws
.handleWsMacro(Value
)
2406 BuildOptions
[Tool
][Attr
] = mws
.handleWsMacro(Value
)
2408 if Module
.AutoGenVersion
< 0x00010005 and self
.Workspace
.UniFlag
is not None:
2410 # Override UNI flag only for EDK module.
2412 BuildOptions
['BUILD']['FLAGS'] = self
.Workspace
.UniFlag
2413 return BuildOptions
, BuildRuleOrder
2416 # extend lists contained in a dictionary with lists stored in another dictionary
2417 # if CopyToDict is not derived from DefaultDict(list) then this may raise exception
2419 def ExtendCopyDictionaryLists(CopyToDict
, CopyFromDict
):
2420 for Key
in CopyFromDict
:
2421 CopyToDict
[Key
].extend(CopyFromDict
[Key
])
2423 # Create a directory specified by a set of path elements and return the full path
2424 def _MakeDir(PathList
):
2425 RetVal
= path
.join(*PathList
)
2426 CreateDirectory(RetVal
)
2429 ## ModuleAutoGen class
2431 # This class encapsules the AutoGen behaviors for the build tools. In addition to
2432 # the generation of AutoGen.h and AutoGen.c, it will generate *.depex file according
2433 # to the [depex] section in module's inf file.
2435 class ModuleAutoGen(AutoGen
):
2436 # call super().__init__ then call the worker function with different parameter count
2437 def __init__(self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
2438 if not hasattr(self
, "_Init"):
2439 super(ModuleAutoGen
, self
).__init
__(Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
)
2440 self
._InitWorker
(Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
)
2443 ## Cache the timestamps of metafiles of every module in a class attribute
2447 def __new__(cls
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
2448 # check if this module is employed by active platform
2449 if not PlatformAutoGen(Workspace
, args
[0], Target
, Toolchain
, Arch
).ValidModule(MetaFile
):
2450 EdkLogger
.verbose("Module [%s] for [%s] is not employed by active platform\n" \
2453 return super(ModuleAutoGen
, cls
).__new
__(cls
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
)
2455 ## Initialize ModuleAutoGen
2457 # @param Workspace EdkIIWorkspaceBuild object
2458 # @param ModuleFile The path of module file
2459 # @param Target Build target (DEBUG, RELEASE)
2460 # @param Toolchain Name of tool chain
2461 # @param Arch The arch the module supports
2462 # @param PlatformFile Platform meta-file
2464 def _InitWorker(self
, Workspace
, ModuleFile
, Target
, Toolchain
, Arch
, PlatformFile
):
2465 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "AutoGen module [%s] [%s]" % (ModuleFile
, Arch
))
2466 GlobalData
.gProcessingFile
= "%s [%s, %s, %s]" % (ModuleFile
, Arch
, Toolchain
, Target
)
2468 self
.Workspace
= Workspace
2469 self
.WorkspaceDir
= Workspace
.WorkspaceDir
2470 self
.MetaFile
= ModuleFile
2471 self
.PlatformInfo
= PlatformAutoGen(Workspace
, PlatformFile
, Target
, Toolchain
, Arch
)
2473 self
.SourceDir
= self
.MetaFile
.SubDir
2474 self
.SourceDir
= mws
.relpath(self
.SourceDir
, self
.WorkspaceDir
)
2476 self
.SourceOverrideDir
= None
2477 # use overrided path defined in DSC file
2478 if self
.MetaFile
.Key
in GlobalData
.gOverrideDir
:
2479 self
.SourceOverrideDir
= GlobalData
.gOverrideDir
[self
.MetaFile
.Key
]
2481 self
.ToolChain
= Toolchain
2482 self
.BuildTarget
= Target
2484 self
.ToolChainFamily
= self
.PlatformInfo
.ToolChainFamily
2485 self
.BuildRuleFamily
= self
.PlatformInfo
.BuildRuleFamily
2487 self
.IsCodeFileCreated
= False
2488 self
.IsAsBuiltInfCreated
= False
2489 self
.DepexGenerated
= False
2491 self
.BuildDatabase
= self
.Workspace
.BuildDatabase
2492 self
.BuildRuleOrder
= None
2495 self
._PcdComments
= OrderedListDict()
2496 self
._GuidComments
= OrderedListDict()
2497 self
._ProtocolComments
= OrderedListDict()
2498 self
._PpiComments
= OrderedListDict()
2499 self
._BuildTargets
= None
2500 self
._IntroBuildTargetList
= None
2501 self
._FinalBuildTargetList
= None
2502 self
._FileTypes
= None
2504 self
.AutoGenDepSet
= set()
2505 self
.ReferenceModules
= []
2510 return "%s [%s]" % (self
.MetaFile
, self
.Arch
)
2512 # Get FixedAtBuild Pcds of this Module
2514 def FixedAtBuildPcds(self
):
2516 for Pcd
in self
.ModulePcdList
:
2517 if Pcd
.Type
!= TAB_PCDS_FIXED_AT_BUILD
:
2519 if Pcd
not in RetVal
:
2524 def FixedVoidTypePcds(self
):
2526 for Pcd
in self
.FixedAtBuildPcds
:
2527 if Pcd
.DatumType
== TAB_VOID
:
2528 if '{}.{}'.format(Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) not in RetVal
:
2529 RetVal
['{}.{}'.format(Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
)] = Pcd
.DefaultValue
2533 def UniqueBaseName(self
):
2534 BaseName
= self
.Name
2535 for Module
in self
.PlatformInfo
.ModuleAutoGenList
:
2536 if Module
.MetaFile
== self
.MetaFile
:
2538 if Module
.Name
== self
.Name
:
2539 if uuid
.UUID(Module
.Guid
) == uuid
.UUID(self
.Guid
):
2540 EdkLogger
.error("build", FILE_DUPLICATED
, 'Modules have same BaseName and FILE_GUID:\n'
2541 ' %s\n %s' % (Module
.MetaFile
, self
.MetaFile
))
2542 BaseName
= '%s_%s' % (self
.Name
, self
.Guid
)
2545 # Macros could be used in build_rule.txt (also Makefile)
2548 return OrderedDict((
2549 ("WORKSPACE" ,self
.WorkspaceDir
),
2550 ("MODULE_NAME" ,self
.Name
),
2551 ("MODULE_NAME_GUID" ,self
.UniqueBaseName
),
2552 ("MODULE_GUID" ,self
.Guid
),
2553 ("MODULE_VERSION" ,self
.Version
),
2554 ("MODULE_TYPE" ,self
.ModuleType
),
2555 ("MODULE_FILE" ,str(self
.MetaFile
)),
2556 ("MODULE_FILE_BASE_NAME" ,self
.MetaFile
.BaseName
),
2557 ("MODULE_RELATIVE_DIR" ,self
.SourceDir
),
2558 ("MODULE_DIR" ,self
.SourceDir
),
2559 ("BASE_NAME" ,self
.Name
),
2560 ("ARCH" ,self
.Arch
),
2561 ("TOOLCHAIN" ,self
.ToolChain
),
2562 ("TOOLCHAIN_TAG" ,self
.ToolChain
),
2563 ("TOOL_CHAIN_TAG" ,self
.ToolChain
),
2564 ("TARGET" ,self
.BuildTarget
),
2565 ("BUILD_DIR" ,self
.PlatformInfo
.BuildDir
),
2566 ("BIN_DIR" ,os
.path
.join(self
.PlatformInfo
.BuildDir
, self
.Arch
)),
2567 ("LIB_DIR" ,os
.path
.join(self
.PlatformInfo
.BuildDir
, self
.Arch
)),
2568 ("MODULE_BUILD_DIR" ,self
.BuildDir
),
2569 ("OUTPUT_DIR" ,self
.OutputDir
),
2570 ("DEBUG_DIR" ,self
.DebugDir
),
2571 ("DEST_DIR_OUTPUT" ,self
.OutputDir
),
2572 ("DEST_DIR_DEBUG" ,self
.DebugDir
),
2573 ("PLATFORM_NAME" ,self
.PlatformInfo
.Name
),
2574 ("PLATFORM_GUID" ,self
.PlatformInfo
.Guid
),
2575 ("PLATFORM_VERSION" ,self
.PlatformInfo
.Version
),
2576 ("PLATFORM_RELATIVE_DIR" ,self
.PlatformInfo
.SourceDir
),
2577 ("PLATFORM_DIR" ,mws
.join(self
.WorkspaceDir
, self
.PlatformInfo
.SourceDir
)),
2578 ("PLATFORM_OUTPUT_DIR" ,self
.PlatformInfo
.OutputDir
),
2579 ("FFS_OUTPUT_DIR" ,self
.FfsOutputDir
)
2582 ## Return the module build data object
2585 return self
.BuildDatabase
[self
.MetaFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
2587 ## Return the module name
2590 return self
.Module
.BaseName
2592 ## Return the module DxsFile if exist
2595 return self
.Module
.DxsFile
2597 ## Return the module meta-file GUID
2601 # To build same module more than once, the module path with FILE_GUID overridden has
2602 # the file name FILE_GUIDmodule.inf, but the relative path (self.MetaFile.File) is the realy path
2603 # in DSC. The overridden GUID can be retrieved from file name
2605 if os
.path
.basename(self
.MetaFile
.File
) != os
.path
.basename(self
.MetaFile
.Path
):
2607 # Length of GUID is 36
2609 return os
.path
.basename(self
.MetaFile
.Path
)[:36]
2610 return self
.Module
.Guid
2612 ## Return the module version
2615 return self
.Module
.Version
2617 ## Return the module type
2619 def ModuleType(self
):
2620 return self
.Module
.ModuleType
2622 ## Return the component type (for Edk.x style of module)
2624 def ComponentType(self
):
2625 return self
.Module
.ComponentType
2627 ## Return the build type
2629 def BuildType(self
):
2630 return self
.Module
.BuildType
2632 ## Return the PCD_IS_DRIVER setting
2634 def PcdIsDriver(self
):
2635 return self
.Module
.PcdIsDriver
2637 ## Return the autogen version, i.e. module meta-file version
2639 def AutoGenVersion(self
):
2640 return self
.Module
.AutoGenVersion
2642 ## Check if the module is library or not
2644 def IsLibrary(self
):
2645 return bool(self
.Module
.LibraryClass
)
2647 ## Check if the module is binary module or not
2649 def IsBinaryModule(self
):
2650 return self
.Module
.IsBinaryModule
2652 ## Return the directory to store intermediate files of the module
2656 self
.PlatformInfo
.BuildDir
,
2659 self
.MetaFile
.BaseName
2662 ## Return the directory to store the intermediate object files of the mdoule
2664 def OutputDir(self
):
2665 return _MakeDir((self
.BuildDir
, "OUTPUT"))
2667 ## Return the directory path to store ffs file
2669 def FfsOutputDir(self
):
2670 if GlobalData
.gFdfParser
:
2671 return path
.join(self
.PlatformInfo
.BuildDir
, TAB_FV_DIRECTORY
, "Ffs", self
.Guid
+ self
.Name
)
2674 ## Return the directory to store auto-gened source files of the mdoule
2677 return _MakeDir((self
.BuildDir
, "DEBUG"))
2679 ## Return the path of custom file
2681 def CustomMakefile(self
):
2683 for Type
in self
.Module
.CustomMakefile
:
2684 MakeType
= gMakeTypeMap
[Type
] if Type
in gMakeTypeMap
else 'nmake'
2685 if self
.SourceOverrideDir
is not None:
2686 File
= os
.path
.join(self
.SourceOverrideDir
, self
.Module
.CustomMakefile
[Type
])
2687 if not os
.path
.exists(File
):
2688 File
= os
.path
.join(self
.SourceDir
, self
.Module
.CustomMakefile
[Type
])
2690 File
= os
.path
.join(self
.SourceDir
, self
.Module
.CustomMakefile
[Type
])
2691 RetVal
[MakeType
] = File
2694 ## Return the directory of the makefile
2696 # @retval string The directory string of module's makefile
2699 def MakeFileDir(self
):
2700 return self
.BuildDir
2702 ## Return build command string
2704 # @retval string Build command string
2707 def BuildCommand(self
):
2708 return self
.PlatformInfo
.BuildCommand
2710 ## Get object list of all packages the module and its dependent libraries belong to
2712 # @retval list The list of package object
2715 def DerivedPackageList(self
):
2717 for M
in [self
.Module
] + self
.DependentLibraryList
:
2718 for Package
in M
.Packages
:
2719 if Package
in PackageList
:
2721 PackageList
.append(Package
)
2724 ## Get the depex string
2726 # @return : a string contain all depex expresion.
2727 def _GetDepexExpresionString(self
):
2730 ## DPX_SOURCE IN Define section.
2731 if self
.Module
.DxsFile
:
2733 for M
in [self
.Module
] + self
.DependentLibraryList
:
2734 Filename
= M
.MetaFile
.Path
2735 InfObj
= InfSectionParser
.InfSectionParser(Filename
)
2736 DepexExpresionList
= InfObj
.GetDepexExpresionList()
2737 for DepexExpresion
in DepexExpresionList
:
2738 for key
in DepexExpresion
:
2739 Arch
, ModuleType
= key
2740 DepexExpr
= [x
for x
in DepexExpresion
[key
] if not str(x
).startswith('#')]
2741 # the type of build module is USER_DEFINED.
2742 # All different DEPEX section tags would be copied into the As Built INF file
2743 # and there would be separate DEPEX section tags
2744 if self
.ModuleType
.upper() == SUP_MODULE_USER_DEFINED
:
2745 if (Arch
.upper() == self
.Arch
.upper()) and (ModuleType
.upper() != TAB_ARCH_COMMON
):
2746 DepexList
.append({(Arch
, ModuleType
): DepexExpr
})
2748 if Arch
.upper() == TAB_ARCH_COMMON
or \
2749 (Arch
.upper() == self
.Arch
.upper() and \
2750 ModuleType
.upper() in [TAB_ARCH_COMMON
, self
.ModuleType
.upper()]):
2751 DepexList
.append({(Arch
, ModuleType
): DepexExpr
})
2753 #the type of build module is USER_DEFINED.
2754 if self
.ModuleType
.upper() == SUP_MODULE_USER_DEFINED
:
2755 for Depex
in DepexList
:
2757 DepexStr
+= '[Depex.%s.%s]\n' % key
2758 DepexStr
+= '\n'.join('# '+ val
for val
in Depex
[key
])
2761 return '[Depex.%s]\n' % self
.Arch
2764 #the type of build module not is USER_DEFINED.
2766 for Depex
in DepexList
:
2771 for D
in Depex
.values():
2772 DepexStr
+= ' '.join(val
for val
in D
)
2773 Index
= DepexStr
.find('END')
2774 if Index
> -1 and Index
== len(DepexStr
) - 3:
2775 DepexStr
= DepexStr
[:-3]
2776 DepexStr
= DepexStr
.strip()
2779 DepexStr
= DepexStr
.lstrip('(').rstrip(')').strip()
2781 return '[Depex.%s]\n' % self
.Arch
2782 return '[Depex.%s]\n# ' % self
.Arch
+ DepexStr
2784 ## Merge dependency expression
2786 # @retval list The token list of the dependency expression after parsed
2789 def DepexList(self
):
2790 if self
.DxsFile
or self
.IsLibrary
or TAB_DEPENDENCY_EXPRESSION_FILE
in self
.FileTypes
:
2795 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion
2797 for M
in [self
.Module
] + self
.DependentLibraryList
:
2799 for D
in M
.Depex
[self
.Arch
, self
.ModuleType
]:
2801 DepexList
.append('AND')
2802 DepexList
.append('(')
2803 #replace D with value if D is FixedAtBuild PCD
2807 NewList
.append(item
)
2809 if item
not in self
._FixedPcdVoidTypeDict
:
2810 EdkLogger
.error("build", FORMAT_INVALID
, "{} used in [Depex] section should be used as FixedAtBuild type and VOID* datum type in the module.".format(item
))
2812 Value
= self
._FixedPcdVoidTypeDict
[item
]
2813 if len(Value
.split(',')) != 16:
2814 EdkLogger
.error("build", FORMAT_INVALID
,
2815 "{} used in [Depex] section should be used as FixedAtBuild type and VOID* datum type and 16 bytes in the module.".format(item
))
2816 NewList
.append(Value
)
2817 DepexList
.extend(NewList
)
2818 if DepexList
[-1] == 'END': # no need of a END at this time
2820 DepexList
.append(')')
2823 EdkLogger
.verbose("DEPEX[%s] (+%s) = %s" % (self
.Name
, M
.BaseName
, DepexList
))
2824 if 'BEFORE' in DepexList
or 'AFTER' in DepexList
:
2826 if len(DepexList
) > 0:
2827 EdkLogger
.verbose('')
2828 return {self
.ModuleType
:DepexList
}
2830 ## Merge dependency expression
2832 # @retval list The token list of the dependency expression after parsed
2835 def DepexExpressionDict(self
):
2836 if self
.DxsFile
or self
.IsLibrary
or TAB_DEPENDENCY_EXPRESSION_FILE
in self
.FileTypes
:
2839 DepexExpressionString
= ''
2841 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion
2843 for M
in [self
.Module
] + self
.DependentLibraryList
:
2845 for D
in M
.DepexExpression
[self
.Arch
, self
.ModuleType
]:
2846 if DepexExpressionString
!= '':
2847 DepexExpressionString
+= ' AND '
2848 DepexExpressionString
+= '('
2849 DepexExpressionString
+= D
2850 DepexExpressionString
= DepexExpressionString
.rstrip('END').strip()
2851 DepexExpressionString
+= ')'
2854 EdkLogger
.verbose("DEPEX[%s] (+%s) = %s" % (self
.Name
, M
.BaseName
, DepexExpressionString
))
2855 if 'BEFORE' in DepexExpressionString
or 'AFTER' in DepexExpressionString
:
2857 if len(DepexExpressionString
) > 0:
2858 EdkLogger
.verbose('')
2860 return {self
.ModuleType
:DepexExpressionString
}
2862 # Get the tiano core user extension, it is contain dependent library.
2863 # @retval: a list contain tiano core userextension.
2865 def _GetTianoCoreUserExtensionList(self
):
2866 TianoCoreUserExtentionList
= []
2867 for M
in [self
.Module
] + self
.DependentLibraryList
:
2868 Filename
= M
.MetaFile
.Path
2869 InfObj
= InfSectionParser
.InfSectionParser(Filename
)
2870 TianoCoreUserExtenList
= InfObj
.GetUserExtensionTianoCore()
2871 for TianoCoreUserExtent
in TianoCoreUserExtenList
:
2872 for Section
in TianoCoreUserExtent
:
2873 ItemList
= Section
.split(TAB_SPLIT
)
2875 if len(ItemList
) == 4:
2877 if Arch
.upper() == TAB_ARCH_COMMON
or Arch
.upper() == self
.Arch
.upper():
2879 TianoCoreList
.extend([TAB_SECTION_START
+ Section
+ TAB_SECTION_END
])
2880 TianoCoreList
.extend(TianoCoreUserExtent
[Section
][:])
2881 TianoCoreList
.append('\n')
2882 TianoCoreUserExtentionList
.append(TianoCoreList
)
2884 return TianoCoreUserExtentionList
2886 ## Return the list of specification version required for the module
2888 # @retval list The list of specification defined in module file
2891 def Specification(self
):
2892 return self
.Module
.Specification
2894 ## Tool option for the module build
2896 # @param PlatformInfo The object of PlatformBuildInfo
2897 # @retval dict The dict containing valid options
2900 def BuildOption(self
):
2901 RetVal
, self
.BuildRuleOrder
= self
.PlatformInfo
.ApplyBuildOption(self
.Module
)
2902 if self
.BuildRuleOrder
:
2903 self
.BuildRuleOrder
= ['.%s' % Ext
for Ext
in self
.BuildRuleOrder
.split()]
2906 ## Get include path list from tool option for the module build
2908 # @retval list The include path list
2911 def BuildOptionIncPathList(self
):
2913 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT
2914 # is the former use /I , the Latter used -I to specify include directories
2916 if self
.PlatformInfo
.ToolChainFamily
in (TAB_COMPILER_MSFT
):
2917 BuildOptIncludeRegEx
= gBuildOptIncludePatternMsft
2918 elif self
.PlatformInfo
.ToolChainFamily
in ('INTEL', 'GCC', 'RVCT'):
2919 BuildOptIncludeRegEx
= gBuildOptIncludePatternOther
2922 # New ToolChainFamily, don't known whether there is option to specify include directories
2927 for Tool
in ('CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'ASM'):
2929 FlagOption
= self
.BuildOption
[Tool
]['FLAGS']
2933 if self
.ToolChainFamily
!= 'RVCT':
2934 IncPathList
= [NormPath(Path
, self
.Macros
) for Path
in BuildOptIncludeRegEx
.findall(FlagOption
)]
2937 # RVCT may specify a list of directory seperated by commas
2940 for Path
in BuildOptIncludeRegEx
.findall(FlagOption
):
2941 PathList
= GetSplitList(Path
, TAB_COMMA_SPLIT
)
2942 IncPathList
.extend(NormPath(PathEntry
, self
.Macros
) for PathEntry
in PathList
)
2945 # EDK II modules must not reference header files outside of the packages they depend on or
2946 # within the module's directory tree. Report error if violation.
2948 if self
.AutoGenVersion
>= 0x00010005:
2949 for Path
in IncPathList
:
2950 if (Path
not in self
.IncludePathList
) and (CommonPath([Path
, self
.MetaFile
.Dir
]) != self
.MetaFile
.Dir
):
2951 ErrMsg
= "The include directory for the EDK II module in this line is invalid %s specified in %s FLAGS '%s'" % (Path
, Tool
, FlagOption
)
2952 EdkLogger
.error("build",
2955 File
=str(self
.MetaFile
))
2956 RetVal
+= IncPathList
2959 ## Return a list of files which can be built from source
2961 # What kind of files can be built is determined by build rules in
2962 # $(CONF_DIRECTORY)/build_rule.txt and toolchain family.
2965 def SourceFileList(self
):
2967 ToolChainTagSet
= {"", "*", self
.ToolChain
}
2968 ToolChainFamilySet
= {"", "*", self
.ToolChainFamily
, self
.BuildRuleFamily
}
2969 for F
in self
.Module
.Sources
:
2971 if F
.TagName
not in ToolChainTagSet
:
2972 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "The toolchain [%s] for processing file [%s] is found, "
2973 "but [%s] is currently used" % (F
.TagName
, str(F
), self
.ToolChain
))
2975 # match tool chain family or build rule family
2976 if F
.ToolChainFamily
not in ToolChainFamilySet
:
2979 "The file [%s] must be built by tools of [%s], " \
2980 "but current toolchain family is [%s], buildrule family is [%s]" \
2981 % (str(F
), F
.ToolChainFamily
, self
.ToolChainFamily
, self
.BuildRuleFamily
))
2984 # add the file path into search path list for file including
2985 if F
.Dir
not in self
.IncludePathList
and self
.AutoGenVersion
>= 0x00010005:
2986 self
.IncludePathList
.insert(0, F
.Dir
)
2989 self
._MatchBuildRuleOrder
(RetVal
)
2992 self
._ApplyBuildRule
(F
, TAB_UNKNOWN_FILE
)
2995 def _MatchBuildRuleOrder(self
, FileList
):
2998 for SingleFile
in FileList
:
2999 if self
.BuildRuleOrder
and SingleFile
.Ext
in self
.BuildRuleOrder
and SingleFile
.Ext
in self
.BuildRules
:
3000 key
= SingleFile
.Path
.split(SingleFile
.Ext
)[0]
3001 if key
in Order_Dict
:
3002 Order_Dict
[key
].append(SingleFile
.Ext
)
3004 Order_Dict
[key
] = [SingleFile
.Ext
]
3007 for F
in Order_Dict
:
3008 if len(Order_Dict
[F
]) > 1:
3009 Order_Dict
[F
].sort(key
=lambda i
: self
.BuildRuleOrder
.index(i
))
3010 for Ext
in Order_Dict
[F
][1:]:
3011 RemoveList
.append(F
+ Ext
)
3013 for item
in RemoveList
:
3014 FileList
.remove(item
)
3018 ## Return the list of unicode files
3020 def UnicodeFileList(self
):
3021 return self
.FileTypes
.get(TAB_UNICODE_FILE
,[])
3023 ## Return the list of vfr files
3025 def VfrFileList(self
):
3026 return self
.FileTypes
.get(TAB_VFR_FILE
, [])
3028 ## Return the list of Image Definition files
3030 def IdfFileList(self
):
3031 return self
.FileTypes
.get(TAB_IMAGE_FILE
,[])
3033 ## Return a list of files which can be built from binary
3035 # "Build" binary files are just to copy them to build directory.
3037 # @retval list The list of files which can be built later
3040 def BinaryFileList(self
):
3042 for F
in self
.Module
.Binaries
:
3043 if F
.Target
not in [TAB_ARCH_COMMON
, '*'] and F
.Target
!= self
.BuildTarget
:
3046 self
._ApplyBuildRule
(F
, F
.Type
, BinaryFileList
=RetVal
)
3050 def BuildRules(self
):
3052 BuildRuleDatabase
= self
.PlatformInfo
.BuildRule
3053 for Type
in BuildRuleDatabase
.FileTypeList
:
3054 #first try getting build rule by BuildRuleFamily
3055 RuleObject
= BuildRuleDatabase
[Type
, self
.BuildType
, self
.Arch
, self
.BuildRuleFamily
]
3057 # build type is always module type, but ...
3058 if self
.ModuleType
!= self
.BuildType
:
3059 RuleObject
= BuildRuleDatabase
[Type
, self
.ModuleType
, self
.Arch
, self
.BuildRuleFamily
]
3060 #second try getting build rule by ToolChainFamily
3062 RuleObject
= BuildRuleDatabase
[Type
, self
.BuildType
, self
.Arch
, self
.ToolChainFamily
]
3064 # build type is always module type, but ...
3065 if self
.ModuleType
!= self
.BuildType
:
3066 RuleObject
= BuildRuleDatabase
[Type
, self
.ModuleType
, self
.Arch
, self
.ToolChainFamily
]
3069 RuleObject
= RuleObject
.Instantiate(self
.Macros
)
3070 RetVal
[Type
] = RuleObject
3071 for Ext
in RuleObject
.SourceFileExtList
:
3072 RetVal
[Ext
] = RuleObject
3075 def _ApplyBuildRule(self
, File
, FileType
, BinaryFileList
=None):
3076 if self
._BuildTargets
is None:
3077 self
._IntroBuildTargetList
= set()
3078 self
._FinalBuildTargetList
= set()
3079 self
._BuildTargets
= defaultdict(set)
3080 self
._FileTypes
= defaultdict(set)
3082 if not BinaryFileList
:
3083 BinaryFileList
= self
.BinaryFileList
3085 SubDirectory
= os
.path
.join(self
.OutputDir
, File
.SubDir
)
3086 if not os
.path
.exists(SubDirectory
):
3087 CreateDirectory(SubDirectory
)
3093 # Make sure to get build rule order value
3097 while Index
< len(SourceList
):
3098 Source
= SourceList
[Index
]
3102 CreateDirectory(Source
.Dir
)
3104 if File
.IsBinary
and File
== Source
and File
in BinaryFileList
:
3105 # Skip all files that are not binary libraries
3106 if not self
.IsLibrary
:
3108 RuleObject
= self
.BuildRules
[TAB_DEFAULT_BINARY_FILE
]
3109 elif FileType
in self
.BuildRules
:
3110 RuleObject
= self
.BuildRules
[FileType
]
3111 elif Source
.Ext
in self
.BuildRules
:
3112 RuleObject
= self
.BuildRules
[Source
.Ext
]
3114 # stop at no more rules
3116 self
._FinalBuildTargetList
.add(LastTarget
)
3119 FileType
= RuleObject
.SourceFileType
3120 self
._FileTypes
[FileType
].add(Source
)
3122 # stop at STATIC_LIBRARY for library
3123 if self
.IsLibrary
and FileType
== TAB_STATIC_LIBRARY
:
3125 self
._FinalBuildTargetList
.add(LastTarget
)
3128 Target
= RuleObject
.Apply(Source
, self
.BuildRuleOrder
)
3131 self
._FinalBuildTargetList
.add(LastTarget
)
3133 elif not Target
.Outputs
:
3134 # Only do build for target with outputs
3135 self
._FinalBuildTargetList
.add(Target
)
3137 self
._BuildTargets
[FileType
].add(Target
)
3139 if not Source
.IsBinary
and Source
== File
:
3140 self
._IntroBuildTargetList
.add(Target
)
3142 # to avoid cyclic rule
3143 if FileType
in RuleChain
:
3146 RuleChain
.add(FileType
)
3147 SourceList
.extend(Target
.Outputs
)
3149 FileType
= TAB_UNKNOWN_FILE
3153 if self
._BuildTargets
is None:
3154 self
._IntroBuildTargetList
= set()
3155 self
._FinalBuildTargetList
= set()
3156 self
._BuildTargets
= defaultdict(set)
3157 self
._FileTypes
= defaultdict(set)
3159 #TRICK: call SourceFileList property to apply build rule for source files
3162 #TRICK: call _GetBinaryFileList to apply build rule for binary files
3165 return self
._BuildTargets
3168 def IntroTargetList(self
):
3170 return self
._IntroBuildTargetList
3173 def CodaTargetList(self
):
3175 return self
._FinalBuildTargetList
3178 def FileTypes(self
):
3180 return self
._FileTypes
3182 ## Get the list of package object the module depends on
3184 # @retval list The package object list
3187 def DependentPackageList(self
):
3188 return self
.Module
.Packages
3190 ## Return the list of auto-generated code file
3192 # @retval list The list of auto-generated file
3195 def AutoGenFileList(self
):
3196 AutoGenUniIdf
= self
.BuildType
!= 'UEFI_HII'
3197 UniStringBinBuffer
= BytesIO()
3198 IdfGenBinBuffer
= BytesIO()
3200 AutoGenC
= TemplateString()
3201 AutoGenH
= TemplateString()
3202 StringH
= TemplateString()
3203 StringIdf
= TemplateString()
3204 GenC
.CreateCode(self
, AutoGenC
, AutoGenH
, StringH
, AutoGenUniIdf
, UniStringBinBuffer
, StringIdf
, AutoGenUniIdf
, IdfGenBinBuffer
)
3206 # AutoGen.c is generated if there are library classes in inf, or there are object files
3208 if str(AutoGenC
) != "" and (len(self
.Module
.LibraryClasses
) > 0
3209 or TAB_OBJECT_FILE
in self
.FileTypes
):
3210 AutoFile
= PathClass(gAutoGenCodeFileName
, self
.DebugDir
)
3211 RetVal
[AutoFile
] = str(AutoGenC
)
3212 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3213 if str(AutoGenH
) != "":
3214 AutoFile
= PathClass(gAutoGenHeaderFileName
, self
.DebugDir
)
3215 RetVal
[AutoFile
] = str(AutoGenH
)
3216 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3217 if str(StringH
) != "":
3218 AutoFile
= PathClass(gAutoGenStringFileName
% {"module_name":self
.Name
}, self
.DebugDir
)
3219 RetVal
[AutoFile
] = str(StringH
)
3220 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3221 if UniStringBinBuffer
is not None and UniStringBinBuffer
.getvalue() != "":
3222 AutoFile
= PathClass(gAutoGenStringFormFileName
% {"module_name":self
.Name
}, self
.OutputDir
)
3223 RetVal
[AutoFile
] = UniStringBinBuffer
.getvalue()
3224 AutoFile
.IsBinary
= True
3225 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3226 if UniStringBinBuffer
is not None:
3227 UniStringBinBuffer
.close()
3228 if str(StringIdf
) != "":
3229 AutoFile
= PathClass(gAutoGenImageDefFileName
% {"module_name":self
.Name
}, self
.DebugDir
)
3230 RetVal
[AutoFile
] = str(StringIdf
)
3231 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3232 if IdfGenBinBuffer
is not None and IdfGenBinBuffer
.getvalue() != "":
3233 AutoFile
= PathClass(gAutoGenIdfFileName
% {"module_name":self
.Name
}, self
.OutputDir
)
3234 RetVal
[AutoFile
] = IdfGenBinBuffer
.getvalue()
3235 AutoFile
.IsBinary
= True
3236 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3237 if IdfGenBinBuffer
is not None:
3238 IdfGenBinBuffer
.close()
3241 ## Return the list of library modules explicitly or implicityly used by this module
3243 def DependentLibraryList(self
):
3244 # only merge library classes and PCD for non-library module
3247 if self
.AutoGenVersion
< 0x00010005:
3248 return self
.PlatformInfo
.ResolveLibraryReference(self
.Module
)
3249 return self
.PlatformInfo
.ApplyLibraryInstance(self
.Module
)
3251 ## Get the list of PCDs from current module
3253 # @retval list The list of PCD
3256 def ModulePcdList(self
):
3257 # apply PCD settings from platform
3258 RetVal
= self
.PlatformInfo
.ApplyPcdSetting(self
.Module
, self
.Module
.Pcds
)
3259 ExtendCopyDictionaryLists(self
._PcdComments
, self
.Module
.PcdComments
)
3262 ## Get the list of PCDs from dependent libraries
3264 # @retval list The list of PCD
3267 def LibraryPcdList(self
):
3272 # get PCDs from dependent libraries
3273 for Library
in self
.DependentLibraryList
:
3274 PcdsInLibrary
= OrderedDict()
3275 ExtendCopyDictionaryLists(self
._PcdComments
, Library
.PcdComments
)
3276 for Key
in Library
.Pcds
:
3277 # skip duplicated PCDs
3278 if Key
in self
.Module
.Pcds
or Key
in Pcds
:
3281 PcdsInLibrary
[Key
] = copy
.copy(Library
.Pcds
[Key
])
3282 RetVal
.extend(self
.PlatformInfo
.ApplyPcdSetting(self
.Module
, PcdsInLibrary
, Library
=Library
))
3285 ## Get the GUID value mapping
3287 # @retval dict The mapping between GUID cname and its value
3291 RetVal
= OrderedDict(self
.Module
.Guids
)
3292 for Library
in self
.DependentLibraryList
:
3293 RetVal
.update(Library
.Guids
)
3294 ExtendCopyDictionaryLists(self
._GuidComments
, Library
.GuidComments
)
3295 ExtendCopyDictionaryLists(self
._GuidComments
, self
.Module
.GuidComments
)
3299 def GetGuidsUsedByPcd(self
):
3300 RetVal
= OrderedDict(self
.Module
.GetGuidsUsedByPcd())
3301 for Library
in self
.DependentLibraryList
:
3302 RetVal
.update(Library
.GetGuidsUsedByPcd())
3304 ## Get the protocol value mapping
3306 # @retval dict The mapping between protocol cname and its value
3309 def ProtocolList(self
):
3310 RetVal
= OrderedDict(self
.Module
.Protocols
)
3311 for Library
in self
.DependentLibraryList
:
3312 RetVal
.update(Library
.Protocols
)
3313 ExtendCopyDictionaryLists(self
._ProtocolComments
, Library
.ProtocolComments
)
3314 ExtendCopyDictionaryLists(self
._ProtocolComments
, self
.Module
.ProtocolComments
)
3317 ## Get the PPI value mapping
3319 # @retval dict The mapping between PPI cname and its value
3323 RetVal
= OrderedDict(self
.Module
.Ppis
)
3324 for Library
in self
.DependentLibraryList
:
3325 RetVal
.update(Library
.Ppis
)
3326 ExtendCopyDictionaryLists(self
._PpiComments
, Library
.PpiComments
)
3327 ExtendCopyDictionaryLists(self
._PpiComments
, self
.Module
.PpiComments
)
3330 ## Get the list of include search path
3332 # @retval list The list path
3335 def IncludePathList(self
):
3337 if self
.AutoGenVersion
< 0x00010005:
3338 for Inc
in self
.Module
.Includes
:
3339 if Inc
not in RetVal
:
3342 Inc
= path
.join(Inc
, self
.Arch
.capitalize())
3343 if os
.path
.exists(Inc
) and Inc
not in RetVal
:
3345 # Edk module needs to put DEBUG_DIR at the end of search path and not to use SOURCE_DIR all the time
3346 RetVal
.append(self
.DebugDir
)
3348 RetVal
.append(self
.MetaFile
.Dir
)
3349 RetVal
.append(self
.DebugDir
)
3351 for Package
in self
.Module
.Packages
:
3352 PackageDir
= mws
.join(self
.WorkspaceDir
, Package
.MetaFile
.Dir
)
3353 if PackageDir
not in RetVal
:
3354 RetVal
.append(PackageDir
)
3355 IncludesList
= Package
.Includes
3356 if Package
._PrivateIncludes
:
3357 if not self
.MetaFile
.Path
.startswith(PackageDir
):
3358 IncludesList
= list(set(Package
.Includes
).difference(set(Package
._PrivateIncludes
)))
3359 for Inc
in IncludesList
:
3360 if Inc
not in RetVal
:
3361 RetVal
.append(str(Inc
))
3365 def IncludePathLength(self
):
3366 return sum(len(inc
)+1 for inc
in self
.IncludePathList
)
3368 ## Get HII EX PCDs which maybe used by VFR
3370 # efivarstore used by VFR may relate with HII EX PCDs
3371 # Get the variable name and GUID from efivarstore and HII EX PCD
3372 # List the HII EX PCDs in As Built INF if both name and GUID match.
3374 # @retval list HII EX PCDs
3376 def _GetPcdsMaybeUsedByVfr(self
):
3377 if not self
.SourceFileList
:
3381 for SrcFile
in self
.SourceFileList
:
3382 if SrcFile
.Ext
.lower() != '.vfr':
3384 Vfri
= os
.path
.join(self
.OutputDir
, SrcFile
.BaseName
+ '.i')
3385 if not os
.path
.exists(Vfri
):
3387 VfriFile
= open(Vfri
, 'r')
3388 Content
= VfriFile
.read()
3390 Pos
= Content
.find('efivarstore')
3393 # Make sure 'efivarstore' is the start of efivarstore statement
3394 # In case of the value of 'name' (name = efivarstore) is equal to 'efivarstore'
3397 while Index
>= 0 and Content
[Index
] in ' \t\r\n':
3399 if Index
>= 0 and Content
[Index
] != ';':
3400 Pos
= Content
.find('efivarstore', Pos
+ len('efivarstore'))
3403 # 'efivarstore' must be followed by name and guid
3405 Name
= gEfiVarStoreNamePattern
.search(Content
, Pos
)
3408 Guid
= gEfiVarStoreGuidPattern
.search(Content
, Pos
)
3411 NameArray
= ConvertStringToByteArray('L"' + Name
.group(1) + '"')
3412 NameGuids
.add((NameArray
, GuidStructureStringToGuidString(Guid
.group(1))))
3413 Pos
= Content
.find('efivarstore', Name
.end())
3417 for Pcd
in self
.PlatformInfo
.Platform
.Pcds
.values():
3418 if Pcd
.Type
!= TAB_PCDS_DYNAMIC_EX_HII
:
3420 for SkuInfo
in Pcd
.SkuInfoList
.values():
3421 Value
= GuidValue(SkuInfo
.VariableGuid
, self
.PlatformInfo
.PackageList
, self
.MetaFile
.Path
)
3424 Name
= ConvertStringToByteArray(SkuInfo
.VariableName
)
3425 Guid
= GuidStructureStringToGuidString(Value
)
3426 if (Name
, Guid
) in NameGuids
and Pcd
not in HiiExPcds
:
3427 HiiExPcds
.append(Pcd
)
3432 def _GenOffsetBin(self
):
3434 for SourceFile
in self
.Module
.Sources
:
3435 if SourceFile
.Type
.upper() == ".VFR" :
3437 # search the .map file to find the offset of vfr binary in the PE32+/TE file.
3439 VfrUniBaseName
[SourceFile
.BaseName
] = (SourceFile
.BaseName
+ "Bin")
3440 elif SourceFile
.Type
.upper() == ".UNI" :
3442 # search the .map file to find the offset of Uni strings binary in the PE32+/TE file.
3444 VfrUniBaseName
["UniOffsetName"] = (self
.Name
+ "Strings")
3446 if not VfrUniBaseName
:
3448 MapFileName
= os
.path
.join(self
.OutputDir
, self
.Name
+ ".map")
3449 EfiFileName
= os
.path
.join(self
.OutputDir
, self
.Name
+ ".efi")
3450 VfrUniOffsetList
= GetVariableOffset(MapFileName
, EfiFileName
, VfrUniBaseName
.values())
3451 if not VfrUniOffsetList
:
3454 OutputName
= '%sOffset.bin' % self
.Name
3455 UniVfrOffsetFileName
= os
.path
.join( self
.OutputDir
, OutputName
)
3458 fInputfile
= open(UniVfrOffsetFileName
, "wb+", 0)
3460 EdkLogger
.error("build", FILE_OPEN_FAILURE
, "File open failed for %s" % UniVfrOffsetFileName
, None)
3462 # Use a instance of BytesIO to cache data
3463 fStringIO
= BytesIO('')
3465 for Item
in VfrUniOffsetList
:
3466 if (Item
[0].find("Strings") != -1):
3468 # UNI offset in image.
3470 # { 0x8913c5e0, 0x33f6, 0x4d86, { 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66 } }
3472 UniGuid
= [0xe0, 0xc5, 0x13, 0x89, 0xf6, 0x33, 0x86, 0x4d, 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66]
3473 UniGuid
= [chr(ItemGuid
) for ItemGuid
in UniGuid
]
3474 fStringIO
.write(''.join(UniGuid
))
3475 UniValue
= pack ('Q', int (Item
[1], 16))
3476 fStringIO
.write (UniValue
)
3479 # VFR binary offset in image.
3481 # { 0xd0bc7cb4, 0x6a47, 0x495f, { 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2 } };
3483 VfrGuid
= [0xb4, 0x7c, 0xbc, 0xd0, 0x47, 0x6a, 0x5f, 0x49, 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2]
3484 VfrGuid
= [chr(ItemGuid
) for ItemGuid
in VfrGuid
]
3485 fStringIO
.write(''.join(VfrGuid
))
3486 VfrValue
= pack ('Q', int (Item
[1], 16))
3487 fStringIO
.write (VfrValue
)
3489 # write data into file.
3492 fInputfile
.write (fStringIO
.getvalue())
3494 EdkLogger
.error("build", FILE_WRITE_FAILURE
, "Write data to file %s failed, please check whether the "
3495 "file been locked or using by other applications." %UniVfrOffsetFileName
, None)
3501 ## Create AsBuilt INF file the module
3503 def CreateAsBuiltInf(self
, IsOnlyCopy
= False):
3504 self
.OutputFile
= set()
3505 if IsOnlyCopy
and GlobalData
.gBinCacheDest
:
3506 self
.CopyModuleToCache()
3509 if self
.IsAsBuiltInfCreated
:
3512 # Skip the following code for EDK I inf
3513 if self
.AutoGenVersion
< 0x00010005:
3516 # Skip the following code for libraries
3520 # Skip the following code for modules with no source files
3521 if not self
.SourceFileList
:
3524 # Skip the following code for modules without any binary files
3525 if self
.BinaryFileList
:
3528 ### TODO: How to handles mixed source and binary modules
3530 # Find all DynamicEx and PatchableInModule PCDs used by this module and dependent libraries
3531 # Also find all packages that the DynamicEx PCDs depend on
3536 PcdTokenSpaceList
= []
3537 for Pcd
in self
.ModulePcdList
+ self
.LibraryPcdList
:
3538 if Pcd
.Type
== TAB_PCDS_PATCHABLE_IN_MODULE
:
3539 PatchablePcds
.append(Pcd
)
3540 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, TAB_PCDS_PATCHABLE_IN_MODULE
))
3541 elif Pcd
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
3544 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC_EX
))
3545 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC
))
3546 PcdTokenSpaceList
.append(Pcd
.TokenSpaceGuidCName
)
3547 GuidList
= OrderedDict(self
.GuidList
)
3548 for TokenSpace
in self
.GetGuidsUsedByPcd
:
3549 # If token space is not referred by patch PCD or Ex PCD, remove the GUID from GUID list
3550 # The GUIDs in GUIDs section should really be the GUIDs in source INF or referred by Ex an patch PCDs
3551 if TokenSpace
not in PcdTokenSpaceList
and TokenSpace
in GuidList
:
3552 GuidList
.pop(TokenSpace
)
3553 CheckList
= (GuidList
, self
.PpiList
, self
.ProtocolList
, PcdCheckList
)
3554 for Package
in self
.DerivedPackageList
:
3555 if Package
in Packages
:
3557 BeChecked
= (Package
.Guids
, Package
.Ppis
, Package
.Protocols
, Package
.Pcds
)
3559 for Index
in range(len(BeChecked
)):
3560 for Item
in CheckList
[Index
]:
3561 if Item
in BeChecked
[Index
]:
3562 Packages
.append(Package
)
3568 VfrPcds
= self
._GetPcdsMaybeUsedByVfr
()
3569 for Pkg
in self
.PlatformInfo
.PackageList
:
3572 for VfrPcd
in VfrPcds
:
3573 if ((VfrPcd
.TokenCName
, VfrPcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC_EX
) in Pkg
.Pcds
or
3574 (VfrPcd
.TokenCName
, VfrPcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC
) in Pkg
.Pcds
):
3575 Packages
.append(Pkg
)
3578 ModuleType
= SUP_MODULE_DXE_DRIVER
if self
.ModuleType
== SUP_MODULE_UEFI_DRIVER
and self
.DepexGenerated
else self
.ModuleType
3579 DriverType
= self
.PcdIsDriver
if self
.PcdIsDriver
else ''
3581 MDefs
= self
.Module
.Defines
3584 'module_name' : self
.Name
,
3585 'module_guid' : Guid
,
3586 'module_module_type' : ModuleType
,
3587 'module_version_string' : [MDefs
['VERSION_STRING']] if 'VERSION_STRING' in MDefs
else [],
3588 'pcd_is_driver_string' : [],
3589 'module_uefi_specification_version' : [],
3590 'module_pi_specification_version' : [],
3591 'module_entry_point' : self
.Module
.ModuleEntryPointList
,
3592 'module_unload_image' : self
.Module
.ModuleUnloadImageList
,
3593 'module_constructor' : self
.Module
.ConstructorList
,
3594 'module_destructor' : self
.Module
.DestructorList
,
3595 'module_shadow' : [MDefs
['SHADOW']] if 'SHADOW' in MDefs
else [],
3596 'module_pci_vendor_id' : [MDefs
['PCI_VENDOR_ID']] if 'PCI_VENDOR_ID' in MDefs
else [],
3597 'module_pci_device_id' : [MDefs
['PCI_DEVICE_ID']] if 'PCI_DEVICE_ID' in MDefs
else [],
3598 'module_pci_class_code' : [MDefs
['PCI_CLASS_CODE']] if 'PCI_CLASS_CODE' in MDefs
else [],
3599 'module_pci_revision' : [MDefs
['PCI_REVISION']] if 'PCI_REVISION' in MDefs
else [],
3600 'module_build_number' : [MDefs
['BUILD_NUMBER']] if 'BUILD_NUMBER' in MDefs
else [],
3601 'module_spec' : [MDefs
['SPEC']] if 'SPEC' in MDefs
else [],
3602 'module_uefi_hii_resource_section' : [MDefs
['UEFI_HII_RESOURCE_SECTION']] if 'UEFI_HII_RESOURCE_SECTION' in MDefs
else [],
3603 'module_uni_file' : [MDefs
['MODULE_UNI_FILE']] if 'MODULE_UNI_FILE' in MDefs
else [],
3604 'module_arch' : self
.Arch
,
3605 'package_item' : [Package
.MetaFile
.File
.replace('\\', '/') for Package
in Packages
],
3607 'patchablepcd_item' : [],
3609 'protocol_item' : [],
3613 'libraryclasses_item' : []
3616 if 'MODULE_UNI_FILE' in MDefs
:
3617 UNIFile
= os
.path
.join(self
.MetaFile
.Dir
, MDefs
['MODULE_UNI_FILE'])
3618 if os
.path
.isfile(UNIFile
):
3619 shutil
.copy2(UNIFile
, self
.OutputDir
)
3621 if self
.AutoGenVersion
> int(gInfSpecVersion
, 0):
3622 AsBuiltInfDict
['module_inf_version'] = '0x%08x' % self
.AutoGenVersion
3624 AsBuiltInfDict
['module_inf_version'] = gInfSpecVersion
3627 AsBuiltInfDict
['pcd_is_driver_string'].append(DriverType
)
3629 if 'UEFI_SPECIFICATION_VERSION' in self
.Specification
:
3630 AsBuiltInfDict
['module_uefi_specification_version'].append(self
.Specification
['UEFI_SPECIFICATION_VERSION'])
3631 if 'PI_SPECIFICATION_VERSION' in self
.Specification
:
3632 AsBuiltInfDict
['module_pi_specification_version'].append(self
.Specification
['PI_SPECIFICATION_VERSION'])
3634 OutputDir
= self
.OutputDir
.replace('\\', '/').strip('/')
3635 DebugDir
= self
.DebugDir
.replace('\\', '/').strip('/')
3636 for Item
in self
.CodaTargetList
:
3637 File
= Item
.Target
.Path
.replace('\\', '/').strip('/').replace(DebugDir
, '').replace(OutputDir
, '').strip('/')
3638 self
.OutputFile
.add(File
)
3639 if os
.path
.isabs(File
):
3640 File
= File
.replace('\\', '/').strip('/').replace(OutputDir
, '').strip('/')
3641 if Item
.Target
.Ext
.lower() == '.aml':
3642 AsBuiltInfDict
['binary_item'].append('ASL|' + File
)
3643 elif Item
.Target
.Ext
.lower() == '.acpi':
3644 AsBuiltInfDict
['binary_item'].append('ACPI|' + File
)
3645 elif Item
.Target
.Ext
.lower() == '.efi':
3646 AsBuiltInfDict
['binary_item'].append('PE32|' + self
.Name
+ '.efi')
3648 AsBuiltInfDict
['binary_item'].append('BIN|' + File
)
3649 if not self
.DepexGenerated
:
3650 DepexFile
= os
.path
.join(self
.OutputDir
, self
.Name
+ '.depex')
3651 if os
.path
.exists(DepexFile
):
3652 self
.DepexGenerated
= True
3653 if self
.DepexGenerated
:
3654 self
.OutputFile
.add(self
.Name
+ '.depex')
3655 if self
.ModuleType
in [SUP_MODULE_PEIM
]:
3656 AsBuiltInfDict
['binary_item'].append('PEI_DEPEX|' + self
.Name
+ '.depex')
3657 elif self
.ModuleType
in [SUP_MODULE_DXE_DRIVER
, SUP_MODULE_DXE_RUNTIME_DRIVER
, SUP_MODULE_DXE_SAL_DRIVER
, SUP_MODULE_UEFI_DRIVER
]:
3658 AsBuiltInfDict
['binary_item'].append('DXE_DEPEX|' + self
.Name
+ '.depex')
3659 elif self
.ModuleType
in [SUP_MODULE_DXE_SMM_DRIVER
]:
3660 AsBuiltInfDict
['binary_item'].append('SMM_DEPEX|' + self
.Name
+ '.depex')
3662 Bin
= self
._GenOffsetBin
()
3664 AsBuiltInfDict
['binary_item'].append('BIN|%s' % Bin
)
3665 self
.OutputFile
.add(Bin
)
3667 for Root
, Dirs
, Files
in os
.walk(OutputDir
):
3669 if File
.lower().endswith('.pdb'):
3670 AsBuiltInfDict
['binary_item'].append('DISPOSABLE|' + File
)
3671 self
.OutputFile
.add(File
)
3672 HeaderComments
= self
.Module
.HeaderComments
3674 for Index
in range(len(HeaderComments
)):
3675 if HeaderComments
[Index
].find('@BinaryHeader') != -1:
3676 HeaderComments
[Index
] = HeaderComments
[Index
].replace('@BinaryHeader', '@file')
3679 AsBuiltInfDict
['header_comments'] = '\n'.join(HeaderComments
[StartPos
:]).replace(':#', '://')
3680 AsBuiltInfDict
['tail_comments'] = '\n'.join(self
.Module
.TailComments
)
3683 (self
.ProtocolList
, self
._ProtocolComments
, 'protocol_item'),
3684 (self
.PpiList
, self
._PpiComments
, 'ppi_item'),
3685 (GuidList
, self
._GuidComments
, 'guid_item')
3687 for Item
in GenList
:
3688 for CName
in Item
[0]:
3689 Comments
= '\n '.join(Item
[1][CName
]) if CName
in Item
[1] else ''
3690 Entry
= Comments
+ '\n ' + CName
if Comments
else CName
3691 AsBuiltInfDict
[Item
[2]].append(Entry
)
3692 PatchList
= parsePcdInfoFromMapFile(
3693 os
.path
.join(self
.OutputDir
, self
.Name
+ '.map'),
3694 os
.path
.join(self
.OutputDir
, self
.Name
+ '.efi')
3697 for Pcd
in PatchablePcds
:
3698 TokenCName
= Pcd
.TokenCName
3699 for PcdItem
in GlobalData
.MixedPcd
:
3700 if (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
3701 TokenCName
= PcdItem
[0]
3703 for PatchPcd
in PatchList
:
3704 if TokenCName
== PatchPcd
[0]:
3709 if Pcd
.DatumType
== 'BOOLEAN':
3710 BoolValue
= Pcd
.DefaultValue
.upper()
3711 if BoolValue
== 'TRUE':
3712 Pcd
.DefaultValue
= '1'
3713 elif BoolValue
== 'FALSE':
3714 Pcd
.DefaultValue
= '0'
3716 if Pcd
.DatumType
in TAB_PCD_NUMERIC_TYPES
:
3717 HexFormat
= '0x%02x'
3718 if Pcd
.DatumType
== TAB_UINT16
:
3719 HexFormat
= '0x%04x'
3720 elif Pcd
.DatumType
== TAB_UINT32
:
3721 HexFormat
= '0x%08x'
3722 elif Pcd
.DatumType
== TAB_UINT64
:
3723 HexFormat
= '0x%016x'
3724 PcdValue
= HexFormat
% int(Pcd
.DefaultValue
, 0)
3726 if Pcd
.MaxDatumSize
is None or Pcd
.MaxDatumSize
== '':
3727 EdkLogger
.error("build", AUTOGEN_ERROR
,
3728 "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
3730 ArraySize
= int(Pcd
.MaxDatumSize
, 0)
3731 PcdValue
= Pcd
.DefaultValue
3732 if PcdValue
[0] != '{':
3734 if PcdValue
[0] == 'L':
3736 PcdValue
= PcdValue
.lstrip('L')
3737 PcdValue
= eval(PcdValue
)
3739 for Index
in range(0, len(PcdValue
)):
3741 CharVal
= ord(PcdValue
[Index
])
3742 NewValue
= NewValue
+ '0x%02x' % (CharVal
& 0x00FF) + ', ' \
3743 + '0x%02x' % (CharVal
>> 8) + ', '
3745 NewValue
= NewValue
+ '0x%02x' % (ord(PcdValue
[Index
]) % 0x100) + ', '
3748 Padding
= Padding
* 2
3749 ArraySize
= ArraySize
/ 2
3750 if ArraySize
< (len(PcdValue
) + 1):
3751 if Pcd
.MaxSizeUserSet
:
3752 EdkLogger
.error("build", AUTOGEN_ERROR
,
3753 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
3756 ArraySize
= len(PcdValue
) + 1
3757 if ArraySize
> len(PcdValue
) + 1:
3758 NewValue
= NewValue
+ Padding
* (ArraySize
- len(PcdValue
) - 1)
3759 PcdValue
= NewValue
+ Padding
.strip().rstrip(',') + '}'
3760 elif len(PcdValue
.split(',')) <= ArraySize
:
3761 PcdValue
= PcdValue
.rstrip('}') + ', 0x00' * (ArraySize
- len(PcdValue
.split(',')))
3764 if Pcd
.MaxSizeUserSet
:
3765 EdkLogger
.error("build", AUTOGEN_ERROR
,
3766 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
3769 ArraySize
= len(PcdValue
) + 1
3770 PcdItem
= '%s.%s|%s|0x%X' % \
3771 (Pcd
.TokenSpaceGuidCName
, TokenCName
, PcdValue
, PatchPcd
[1])
3773 if (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) in self
._PcdComments
:
3774 PcdComments
= '\n '.join(self
._PcdComments
[Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
])
3776 PcdItem
= PcdComments
+ '\n ' + PcdItem
3777 AsBuiltInfDict
['patchablepcd_item'].append(PcdItem
)
3779 for Pcd
in Pcds
+ VfrPcds
:
3782 TokenCName
= Pcd
.TokenCName
3783 for PcdItem
in GlobalData
.MixedPcd
:
3784 if (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
3785 TokenCName
= PcdItem
[0]
3787 if Pcd
.Type
== TAB_PCDS_DYNAMIC_EX_HII
:
3788 for SkuName
in Pcd
.SkuInfoList
:
3789 SkuInfo
= Pcd
.SkuInfoList
[SkuName
]
3790 HiiInfo
= '## %s|%s|%s' % (SkuInfo
.VariableName
, SkuInfo
.VariableGuid
, SkuInfo
.VariableOffset
)
3792 if (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) in self
._PcdComments
:
3793 PcdCommentList
= self
._PcdComments
[Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
][:]
3797 for Index
, Comment
in enumerate(PcdCommentList
):
3798 for Usage
in UsageList
:
3799 if Comment
.find(Usage
) != -1:
3803 if UsageIndex
!= -1:
3804 PcdCommentList
[UsageIndex
] = '## %s %s %s' % (UsageStr
, HiiInfo
, PcdCommentList
[UsageIndex
].replace(UsageStr
, ''))
3806 PcdCommentList
.append('## UNDEFINED ' + HiiInfo
)
3807 PcdComments
= '\n '.join(PcdCommentList
)
3808 PcdEntry
= Pcd
.TokenSpaceGuidCName
+ '.' + TokenCName
3810 PcdEntry
= PcdComments
+ '\n ' + PcdEntry
3811 AsBuiltInfDict
['pcd_item'].append(PcdEntry
)
3812 for Item
in self
.BuildOption
:
3813 if 'FLAGS' in self
.BuildOption
[Item
]:
3814 AsBuiltInfDict
['flags_item'].append('%s:%s_%s_%s_%s_FLAGS = %s' % (self
.ToolChainFamily
, self
.BuildTarget
, self
.ToolChain
, self
.Arch
, Item
, self
.BuildOption
[Item
]['FLAGS'].strip()))
3816 # Generated LibraryClasses section in comments.
3817 for Library
in self
.LibraryAutoGenList
:
3818 AsBuiltInfDict
['libraryclasses_item'].append(Library
.MetaFile
.File
.replace('\\', '/'))
3820 # Generated UserExtensions TianoCore section.
3821 # All tianocore user extensions are copied.
3823 for TianoCore
in self
._GetTianoCoreUserExtensionList
():
3824 UserExtStr
+= '\n'.join(TianoCore
)
3825 ExtensionFile
= os
.path
.join(self
.MetaFile
.Dir
, TianoCore
[1])
3826 if os
.path
.isfile(ExtensionFile
):
3827 shutil
.copy2(ExtensionFile
, self
.OutputDir
)
3828 AsBuiltInfDict
['userextension_tianocore_item'] = UserExtStr
3830 # Generated depex expression section in comments.
3831 DepexExpresion
= self
._GetDepexExpresionString
()
3832 AsBuiltInfDict
['depexsection_item'] = DepexExpresion
if DepexExpresion
else ''
3834 AsBuiltInf
= TemplateString()
3835 AsBuiltInf
.Append(gAsBuiltInfHeaderString
.Replace(AsBuiltInfDict
))
3837 SaveFileOnChange(os
.path
.join(self
.OutputDir
, self
.Name
+ '.inf'), str(AsBuiltInf
), False)
3839 self
.IsAsBuiltInfCreated
= True
3840 if GlobalData
.gBinCacheDest
:
3841 self
.CopyModuleToCache()
3843 def CopyModuleToCache(self
):
3844 FileDir
= path
.join(GlobalData
.gBinCacheDest
, self
.Arch
, self
.SourceDir
, self
.MetaFile
.BaseName
)
3845 CreateDirectory (FileDir
)
3846 HashFile
= path
.join(self
.BuildDir
, self
.Name
+ '.hash')
3847 ModuleFile
= path
.join(self
.OutputDir
, self
.Name
+ '.inf')
3848 if os
.path
.exists(HashFile
):
3849 shutil
.copy2(HashFile
, FileDir
)
3850 if os
.path
.exists(ModuleFile
):
3851 shutil
.copy2(ModuleFile
, FileDir
)
3852 if not self
.OutputFile
:
3853 Ma
= self
.BuildDatabase
[PathClass(ModuleFile
), self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
3854 self
.OutputFile
= Ma
.Binaries
3856 for File
in self
.OutputFile
:
3858 if not os
.path
.isabs(File
):
3859 File
= os
.path
.join(self
.OutputDir
, File
)
3860 if os
.path
.exists(File
):
3861 shutil
.copy2(File
, FileDir
)
3863 def AttemptModuleCacheCopy(self
):
3864 if self
.IsBinaryModule
:
3866 FileDir
= path
.join(GlobalData
.gBinCacheSource
, self
.Arch
, self
.SourceDir
, self
.MetaFile
.BaseName
)
3867 HashFile
= path
.join(FileDir
, self
.Name
+ '.hash')
3868 if os
.path
.exists(HashFile
):
3869 f
= open(HashFile
, 'r')
3870 CacheHash
= f
.read()
3872 if GlobalData
.gModuleHash
[self
.Arch
][self
.Name
]:
3873 if CacheHash
== GlobalData
.gModuleHash
[self
.Arch
][self
.Name
]:
3874 for root
, dir, files
in os
.walk(FileDir
):
3876 if self
.Name
+ '.hash' in f
:
3877 shutil
.copy2(HashFile
, self
.BuildDir
)
3879 File
= path
.join(root
, f
)
3880 shutil
.copy2(File
, self
.OutputDir
)
3881 if self
.Name
== "PcdPeim" or self
.Name
== "PcdDxe":
3882 CreatePcdDatabaseCode(self
, TemplateString(), TemplateString())
3886 ## Create makefile for the module and its dependent libraries
3888 # @param CreateLibraryMakeFile Flag indicating if or not the makefiles of
3889 # dependent libraries will be created
3891 @cached_class_function
3892 def CreateMakeFile(self
, CreateLibraryMakeFile
=True, GenFfsList
= []):
3893 # nest this function inside it's only caller.
3894 def CreateTimeStamp():
3895 FileSet
= {self
.MetaFile
.Path
}
3897 for SourceFile
in self
.Module
.Sources
:
3898 FileSet
.add (SourceFile
.Path
)
3900 for Lib
in self
.DependentLibraryList
:
3901 FileSet
.add (Lib
.MetaFile
.Path
)
3903 for f
in self
.AutoGenDepSet
:
3904 FileSet
.add (f
.Path
)
3906 if os
.path
.exists (self
.TimeStampPath
):
3907 os
.remove (self
.TimeStampPath
)
3908 with
open(self
.TimeStampPath
, 'w+') as file:
3912 # Ignore generating makefile when it is a binary module
3913 if self
.IsBinaryModule
:
3916 self
.GenFfsList
= GenFfsList
3917 if not self
.IsLibrary
and CreateLibraryMakeFile
:
3918 for LibraryAutoGen
in self
.LibraryAutoGenList
:
3919 LibraryAutoGen
.CreateMakeFile()
3924 if len(self
.CustomMakefile
) == 0:
3925 Makefile
= GenMake
.ModuleMakefile(self
)
3927 Makefile
= GenMake
.CustomMakefile(self
)
3928 if Makefile
.Generate():
3929 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated makefile for module %s [%s]" %
3930 (self
.Name
, self
.Arch
))
3932 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Skipped the generation of makefile for module %s [%s]" %
3933 (self
.Name
, self
.Arch
))
3937 def CopyBinaryFiles(self
):
3938 for File
in self
.Module
.Binaries
:
3940 DstPath
= os
.path
.join(self
.OutputDir
, os
.path
.basename(SrcPath
))
3941 CopyLongFilePath(SrcPath
, DstPath
)
3942 ## Create autogen code for the module and its dependent libraries
3944 # @param CreateLibraryCodeFile Flag indicating if or not the code of
3945 # dependent libraries will be created
3947 def CreateCodeFile(self
, CreateLibraryCodeFile
=True):
3948 if self
.IsCodeFileCreated
:
3951 # Need to generate PcdDatabase even PcdDriver is binarymodule
3952 if self
.IsBinaryModule
and self
.PcdIsDriver
!= '':
3953 CreatePcdDatabaseCode(self
, TemplateString(), TemplateString())
3955 if self
.IsBinaryModule
:
3957 self
.CopyBinaryFiles()
3960 if not self
.IsLibrary
and CreateLibraryCodeFile
:
3961 for LibraryAutoGen
in self
.LibraryAutoGenList
:
3962 LibraryAutoGen
.CreateCodeFile()
3968 IgoredAutoGenList
= []
3970 for File
in self
.AutoGenFileList
:
3971 if GenC
.Generate(File
.Path
, self
.AutoGenFileList
[File
], File
.IsBinary
):
3972 #Ignore Edk AutoGen.c
3973 if self
.AutoGenVersion
< 0x00010005 and File
.Name
== 'AutoGen.c':
3976 AutoGenList
.append(str(File
))
3978 IgoredAutoGenList
.append(str(File
))
3980 # Skip the following code for EDK I inf
3981 if self
.AutoGenVersion
< 0x00010005:
3984 for ModuleType
in self
.DepexList
:
3985 # Ignore empty [depex] section or [depex] section for SUP_MODULE_USER_DEFINED module
3986 if len(self
.DepexList
[ModuleType
]) == 0 or ModuleType
== SUP_MODULE_USER_DEFINED
:
3989 Dpx
= GenDepex
.DependencyExpression(self
.DepexList
[ModuleType
], ModuleType
, True)
3990 DpxFile
= gAutoGenDepexFileName
% {"module_name" : self
.Name
}
3992 if len(Dpx
.PostfixNotation
) != 0:
3993 self
.DepexGenerated
= True
3995 if Dpx
.Generate(path
.join(self
.OutputDir
, DpxFile
)):
3996 AutoGenList
.append(str(DpxFile
))
3998 IgoredAutoGenList
.append(str(DpxFile
))
4000 if IgoredAutoGenList
== []:
4001 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated [%s] files for module %s [%s]" %
4002 (" ".join(AutoGenList
), self
.Name
, self
.Arch
))
4003 elif AutoGenList
== []:
4004 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Skipped the generation of [%s] files for module %s [%s]" %
4005 (" ".join(IgoredAutoGenList
), self
.Name
, self
.Arch
))
4007 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated [%s] (skipped %s) files for module %s [%s]" %
4008 (" ".join(AutoGenList
), " ".join(IgoredAutoGenList
), self
.Name
, self
.Arch
))
4010 self
.IsCodeFileCreated
= True
4013 ## Summarize the ModuleAutoGen objects of all libraries used by this module
4015 def LibraryAutoGenList(self
):
4017 for Library
in self
.DependentLibraryList
:
4024 self
.PlatformInfo
.MetaFile
4026 if La
not in RetVal
:
4028 for Lib
in La
.CodaTargetList
:
4029 self
._ApplyBuildRule
(Lib
.Target
, TAB_UNKNOWN_FILE
)
4032 def GenModuleHash(self
):
4033 if self
.Arch
not in GlobalData
.gModuleHash
:
4034 GlobalData
.gModuleHash
[self
.Arch
] = {}
4036 # Add Platform level hash
4037 m
.update(GlobalData
.gPlatformHash
)
4038 # Add Package level hash
4039 if self
.DependentPackageList
:
4040 for Pkg
in sorted(self
.DependentPackageList
, key
=lambda x
: x
.PackageName
):
4041 if Pkg
.PackageName
in GlobalData
.gPackageHash
[self
.Arch
]:
4042 m
.update(GlobalData
.gPackageHash
[self
.Arch
][Pkg
.PackageName
])
4045 if self
.LibraryAutoGenList
:
4046 for Lib
in sorted(self
.LibraryAutoGenList
, key
=lambda x
: x
.Name
):
4047 if Lib
.Name
not in GlobalData
.gModuleHash
[self
.Arch
]:
4049 m
.update(GlobalData
.gModuleHash
[self
.Arch
][Lib
.Name
])
4052 f
= open(str(self
.MetaFile
), 'r')
4056 # Add Module's source files
4057 if self
.SourceFileList
:
4058 for File
in sorted(self
.SourceFileList
, key
=lambda x
: str(x
)):
4059 f
= open(str(File
), 'r')
4064 ModuleHashFile
= path
.join(self
.BuildDir
, self
.Name
+ ".hash")
4065 if self
.Name
not in GlobalData
.gModuleHash
[self
.Arch
]:
4066 GlobalData
.gModuleHash
[self
.Arch
][self
.Name
] = m
.hexdigest()
4067 if GlobalData
.gBinCacheSource
:
4068 if self
.AttemptModuleCacheCopy():
4070 return SaveFileOnChange(ModuleHashFile
, m
.hexdigest(), True)
4072 ## Decide whether we can skip the ModuleAutoGen process
4073 def CanSkipbyHash(self
):
4074 if GlobalData
.gUseHashCache
:
4075 return not self
.GenModuleHash()
4078 ## Decide whether we can skip the ModuleAutoGen process
4079 # If any source file is newer than the module than we cannot skip
4082 if self
.MakeFileDir
in GlobalData
.gSikpAutoGenCache
:
4084 if not os
.path
.exists(self
.TimeStampPath
):
4086 #last creation time of the module
4087 DstTimeStamp
= os
.stat(self
.TimeStampPath
)[8]
4089 SrcTimeStamp
= self
.Workspace
._SrcTimeStamp
4090 if SrcTimeStamp
> DstTimeStamp
:
4093 with
open(self
.TimeStampPath
,'r') as f
:
4095 source
= source
.rstrip('\n')
4096 if not os
.path
.exists(source
):
4098 if source
not in ModuleAutoGen
.TimeDict
:
4099 ModuleAutoGen
.TimeDict
[source
] = os
.stat(source
)[8]
4100 if ModuleAutoGen
.TimeDict
[source
] > DstTimeStamp
:
4102 GlobalData
.gSikpAutoGenCache
.add(self
.MakeFileDir
)
4106 def TimeStampPath(self
):
4107 return os
.path
.join(self
.MakeFileDir
, 'AutoGenTimeStamp')