2 # Generate AutoGen.h, AutoGen.c and *.depex files
4 # Copyright (c) 2007 - 2016, Intel Corporation. All rights reserved.<BR>
5 # This program and the accompanying materials
6 # are licensed and made available under the terms and conditions of the BSD License
7 # which accompanies this distribution. The full text of the license may be found at
8 # http://opensource.org/licenses/bsd-license.php
10 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
16 import Common
.LongFilePathOs
as os
18 import os
.path
as path
25 from StringIO
import StringIO
27 from StrGather
import *
28 from BuildEngine
import BuildRule
30 from Common
.LongFilePathSupport
import CopyLongFilePath
31 from Common
.BuildToolError
import *
32 from Common
.DataType
import *
33 from Common
.Misc
import *
34 from Common
.String
import *
35 import Common
.GlobalData
as GlobalData
36 from GenFds
.FdfParser
import *
37 from CommonDataClass
.CommonClass
import SkuInfoClass
38 from Workspace
.BuildClassObject
import *
39 from GenPatchPcdTable
.GenPatchPcdTable
import parsePcdInfoFromMapFile
40 import Common
.VpdInfoFile
as VpdInfoFile
41 from GenPcdDb
import CreatePcdDatabaseCode
42 from Workspace
.MetaFileCommentParser
import UsageList
43 from Common
.MultipleWorkspace
import MultipleWorkspace
as mws
44 import InfSectionParser
46 ## Regular expression for splitting Dependency Expression string into tokens
47 gDepexTokenPattern
= re
.compile("(\(|\)|\w+| \S+\.inf)")
50 # Match name = variable
52 gEfiVarStoreNamePattern
= re
.compile("\s*name\s*=\s*(\w+)")
54 # The format of guid in efivarstore statement likes following and must be correct:
55 # guid = {0xA04A27f4, 0xDF00, 0x4D42, {0xB5, 0x52, 0x39, 0x51, 0x13, 0x02, 0x11, 0x3D}}
57 gEfiVarStoreGuidPattern
= re
.compile("\s*guid\s*=\s*({.*?{.*?}\s*})")
59 ## Mapping Makefile type
60 gMakeTypeMap
= {"MSFT":"nmake", "GCC":"gmake"}
63 ## Build rule configuration file
64 gDefaultBuildRuleFile
= 'Conf/build_rule.txt'
66 ## Build rule default version
67 AutoGenReqBuildRuleVerNum
= "0.1"
69 ## default file name for AutoGen
70 gAutoGenCodeFileName
= "AutoGen.c"
71 gAutoGenHeaderFileName
= "AutoGen.h"
72 gAutoGenStringFileName
= "%(module_name)sStrDefs.h"
73 gAutoGenStringFormFileName
= "%(module_name)sStrDefs.hpk"
74 gAutoGenDepexFileName
= "%(module_name)s.depex"
76 gInfSpecVersion
= "0x00010017"
79 # Template string to generic AsBuilt INF
81 gAsBuiltInfHeaderString
= TemplateString("""${header_comments}
87 INF_VERSION = ${module_inf_version}
88 BASE_NAME = ${module_name}
89 FILE_GUID = ${module_guid}
90 MODULE_TYPE = ${module_module_type}${BEGIN}
91 VERSION_STRING = ${module_version_string}${END}${BEGIN}
92 PCD_IS_DRIVER = ${pcd_is_driver_string}${END}${BEGIN}
93 UEFI_SPECIFICATION_VERSION = ${module_uefi_specification_version}${END}${BEGIN}
94 PI_SPECIFICATION_VERSION = ${module_pi_specification_version}${END}${BEGIN}
95 ENTRY_POINT = ${module_entry_point}${END}${BEGIN}
96 UNLOAD_IMAGE = ${module_unload_image}${END}${BEGIN}
97 CONSTRUCTOR = ${module_constructor}${END}${BEGIN}
98 DESTRUCTOR = ${module_destructor}${END}${BEGIN}
99 SHADOW = ${module_shadow}${END}${BEGIN}
100 PCI_VENDOR_ID = ${module_pci_vendor_id}${END}${BEGIN}
101 PCI_DEVICE_ID = ${module_pci_device_id}${END}${BEGIN}
102 PCI_CLASS_CODE = ${module_pci_class_code}${END}${BEGIN}
103 PCI_REVISION = ${module_pci_revision}${END}${BEGIN}
104 BUILD_NUMBER = ${module_build_number}${END}${BEGIN}
105 SPEC = ${module_spec}${END}${BEGIN}
106 UEFI_HII_RESOURCE_SECTION = ${module_uefi_hii_resource_section}${END}${BEGIN}
107 MODULE_UNI_FILE = ${module_uni_file}${END}
109 [Packages.${module_arch}]${BEGIN}
110 ${package_item}${END}
112 [Binaries.${module_arch}]${BEGIN}
115 [PatchPcd.${module_arch}]${BEGIN}
119 [Protocols.${module_arch}]${BEGIN}
123 [Ppis.${module_arch}]${BEGIN}
127 [Guids.${module_arch}]${BEGIN}
131 [PcdEx.${module_arch}]${BEGIN}
135 [LibraryClasses.${module_arch}]
136 ## @LIB_INSTANCES${BEGIN}
137 # ${libraryclasses_item}${END}
143 [BuildOptions.${module_arch}]
145 ## ${flags_item}${END}
148 ## Base class for AutoGen
150 # This class just implements the cache mechanism of AutoGen objects.
152 class AutoGen(object):
153 # database to maintain the objects of xxxAutoGen
154 _CACHE_
= {} # (BuildTarget, ToolChain) : {ARCH : {platform file: AutoGen object}}}
158 # @param Class class object of real AutoGen class
159 # (WorkspaceAutoGen, ModuleAutoGen or PlatformAutoGen)
160 # @param Workspace Workspace directory or WorkspaceAutoGen object
161 # @param MetaFile The path of meta file
162 # @param Target Build target
163 # @param Toolchain Tool chain name
164 # @param Arch Target arch
165 # @param *args The specific class related parameters
166 # @param **kwargs The specific class related dict parameters
168 def __new__(Class
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
169 # check if the object has been created
170 Key
= (Target
, Toolchain
)
171 if Key
not in Class
._CACHE
_ or Arch
not in Class
._CACHE
_[Key
] \
172 or MetaFile
not in Class
._CACHE
_[Key
][Arch
]:
173 AutoGenObject
= super(AutoGen
, Class
).__new
__(Class
)
174 # call real constructor
175 if not AutoGenObject
._Init
(Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
177 if Key
not in Class
._CACHE
_:
178 Class
._CACHE
_[Key
] = {}
179 if Arch
not in Class
._CACHE
_[Key
]:
180 Class
._CACHE
_[Key
][Arch
] = {}
181 Class
._CACHE
_[Key
][Arch
][MetaFile
] = AutoGenObject
183 AutoGenObject
= Class
._CACHE
_[Key
][Arch
][MetaFile
]
189 # The file path of platform file will be used to represent hash value of this object
191 # @retval int Hash value of the file path of platform file
194 return hash(self
.MetaFile
)
198 # The file path of platform file will be used to represent this object
200 # @retval string String of platform file path
203 return str(self
.MetaFile
)
206 def __eq__(self
, Other
):
207 return Other
and self
.MetaFile
== Other
209 ## Workspace AutoGen class
211 # This class is used mainly to control the whole platform build for different
212 # architecture. This class will generate top level makefile.
214 class WorkspaceAutoGen(AutoGen
):
215 ## Real constructor of WorkspaceAutoGen
217 # This method behaves the same as __init__ except that it needs explicit invoke
218 # (in super class's __new__ method)
220 # @param WorkspaceDir Root directory of workspace
221 # @param ActivePlatform Meta-file of active platform
222 # @param Target Build target
223 # @param Toolchain Tool chain name
224 # @param ArchList List of architecture of current build
225 # @param MetaFileDb Database containing meta-files
226 # @param BuildConfig Configuration of build
227 # @param ToolDefinition Tool chain definitions
228 # @param FlashDefinitionFile File of flash definition
229 # @param Fds FD list to be generated
230 # @param Fvs FV list to be generated
231 # @param Caps Capsule list to be generated
232 # @param SkuId SKU id from command line
234 def _Init(self
, WorkspaceDir
, ActivePlatform
, Target
, Toolchain
, ArchList
, MetaFileDb
,
235 BuildConfig
, ToolDefinition
, FlashDefinitionFile
='', Fds
=None, Fvs
=None, Caps
=None, SkuId
='', UniFlag
=None,
236 Progress
=None, BuildModule
=None):
243 self
.BuildDatabase
= MetaFileDb
244 self
.MetaFile
= ActivePlatform
245 self
.WorkspaceDir
= WorkspaceDir
246 self
.Platform
= self
.BuildDatabase
[self
.MetaFile
, 'COMMON', Target
, Toolchain
]
247 GlobalData
.gActivePlatform
= self
.Platform
248 self
.BuildTarget
= Target
249 self
.ToolChain
= Toolchain
250 self
.ArchList
= ArchList
252 self
.UniFlag
= UniFlag
254 self
.TargetTxt
= BuildConfig
255 self
.ToolDef
= ToolDefinition
256 self
.FdfFile
= FlashDefinitionFile
257 self
.FdTargetList
= Fds
258 self
.FvTargetList
= Fvs
259 self
.CapTargetList
= Caps
260 self
.AutoGenObjectList
= []
262 # there's many relative directory operations, so ...
263 os
.chdir(self
.WorkspaceDir
)
268 if not self
.ArchList
:
269 ArchList
= set(self
.Platform
.SupArchList
)
271 ArchList
= set(self
.ArchList
) & set(self
.Platform
.SupArchList
)
273 EdkLogger
.error("build", PARAMETER_INVALID
,
274 ExtraData
= "Invalid ARCH specified. [Valid ARCH: %s]" % (" ".join(self
.Platform
.SupArchList
)))
275 elif self
.ArchList
and len(ArchList
) != len(self
.ArchList
):
276 SkippedArchList
= set(self
.ArchList
).symmetric_difference(set(self
.Platform
.SupArchList
))
277 EdkLogger
.verbose("\nArch [%s] is ignored because the platform supports [%s] only!"
278 % (" ".join(SkippedArchList
), " ".join(self
.Platform
.SupArchList
)))
279 self
.ArchList
= tuple(ArchList
)
281 # Validate build target
282 if self
.BuildTarget
not in self
.Platform
.BuildTargets
:
283 EdkLogger
.error("build", PARAMETER_INVALID
,
284 ExtraData
="Build target [%s] is not supported by the platform. [Valid target: %s]"
285 % (self
.BuildTarget
, " ".join(self
.Platform
.BuildTargets
)))
288 # parse FDF file to get PCDs in it, if any
290 self
.FdfFile
= self
.Platform
.FlashDefinition
294 EdkLogger
.info('%-16s = %s' % ("Architecture(s)", ' '.join(self
.ArchList
)))
295 EdkLogger
.info('%-16s = %s' % ("Build target", self
.BuildTarget
))
296 EdkLogger
.info('%-16s = %s' % ("Toolchain", self
.ToolChain
))
298 EdkLogger
.info('\n%-24s = %s' % ("Active Platform", self
.Platform
))
300 EdkLogger
.info('%-24s = %s' % ("Active Module", BuildModule
))
303 EdkLogger
.info('%-24s = %s' % ("Flash Image Definition", self
.FdfFile
))
305 EdkLogger
.verbose("\nFLASH_DEFINITION = %s" % self
.FdfFile
)
308 Progress
.Start("\nProcessing meta-data")
312 # Mark now build in AutoGen Phase
314 GlobalData
.gAutoGenPhase
= True
315 Fdf
= FdfParser(self
.FdfFile
.Path
)
317 GlobalData
.gFdfParser
= Fdf
318 GlobalData
.gAutoGenPhase
= False
319 PcdSet
= Fdf
.Profile
.PcdDict
320 if Fdf
.CurrentFdName
and Fdf
.CurrentFdName
in Fdf
.Profile
.FdDict
:
321 FdDict
= Fdf
.Profile
.FdDict
[Fdf
.CurrentFdName
]
322 for FdRegion
in FdDict
.RegionList
:
323 if str(FdRegion
.RegionType
) is 'FILE' and self
.Platform
.VpdToolGuid
in str(FdRegion
.RegionDataList
):
324 if int(FdRegion
.Offset
) % 8 != 0:
325 EdkLogger
.error("build", FORMAT_INVALID
, 'The VPD Base Address %s must be 8-byte aligned.' % (FdRegion
.Offset
))
326 ModuleList
= Fdf
.Profile
.InfList
327 self
.FdfProfile
= Fdf
.Profile
328 for fvname
in self
.FvTargetList
:
329 if fvname
.upper() not in self
.FdfProfile
.FvDict
:
330 EdkLogger
.error("build", OPTION_VALUE_INVALID
,
331 "No such an FV in FDF file: %s" % fvname
)
333 # In DSC file may use FILE_GUID to override the module, then in the Platform.Modules use FILE_GUIDmodule.inf as key,
334 # but the path (self.MetaFile.Path) is the real path
335 for key
in self
.FdfProfile
.InfDict
:
339 for Arch
in self
.ArchList
:
340 Platform_cache
[Arch
] = self
.BuildDatabase
[self
.MetaFile
, Arch
, Target
, Toolchain
]
341 MetaFile_cache
[Arch
] = []
342 for Pkey
in Platform_cache
[Arch
].Modules
.keys():
343 MetaFile_cache
[Arch
].append(Platform_cache
[Arch
].Modules
[Pkey
].MetaFile
)
344 for Inf
in self
.FdfProfile
.InfDict
[key
]:
345 ModuleFile
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, Arch
)
346 for Arch
in self
.ArchList
:
347 if ModuleFile
in MetaFile_cache
[Arch
]:
350 ModuleData
= self
.BuildDatabase
[ModuleFile
, Arch
, Target
, Toolchain
]
351 if not ModuleData
.IsBinaryModule
:
352 EdkLogger
.error('build', PARSER_ERROR
, "Module %s NOT found in DSC file; Is it really a binary module?" % ModuleFile
)
355 for Arch
in self
.ArchList
:
357 Platform
= self
.BuildDatabase
[self
.MetaFile
, Arch
, Target
, Toolchain
]
359 for Pkey
in Platform
.Modules
.keys():
360 MetaFileList
.append(Platform
.Modules
[Pkey
].MetaFile
)
361 for Inf
in self
.FdfProfile
.InfDict
[key
]:
362 ModuleFile
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, Arch
)
363 if ModuleFile
in MetaFileList
:
365 ModuleData
= self
.BuildDatabase
[ModuleFile
, Arch
, Target
, Toolchain
]
366 if not ModuleData
.IsBinaryModule
:
367 EdkLogger
.error('build', PARSER_ERROR
, "Module %s NOT found in DSC file; Is it really a binary module?" % ModuleFile
)
372 self
.FdfProfile
= None
373 if self
.FdTargetList
:
374 EdkLogger
.info("No flash definition file found. FD [%s] will be ignored." % " ".join(self
.FdTargetList
))
375 self
.FdTargetList
= []
376 if self
.FvTargetList
:
377 EdkLogger
.info("No flash definition file found. FV [%s] will be ignored." % " ".join(self
.FvTargetList
))
378 self
.FvTargetList
= []
379 if self
.CapTargetList
:
380 EdkLogger
.info("No flash definition file found. Capsule [%s] will be ignored." % " ".join(self
.CapTargetList
))
381 self
.CapTargetList
= []
383 # apply SKU and inject PCDs from Flash Definition file
384 for Arch
in self
.ArchList
:
385 Platform
= self
.BuildDatabase
[self
.MetaFile
, Arch
, Target
, Toolchain
]
389 PGen
= PlatformAutoGen(self
, self
.MetaFile
, Target
, Toolchain
, Arch
)
390 if GlobalData
.BuildOptionPcd
:
391 for i
, pcd
in enumerate(GlobalData
.BuildOptionPcd
):
392 if type(pcd
) is tuple:
394 (pcdname
, pcdvalue
) = pcd
.split('=')
396 EdkLogger
.error('build', AUTOGEN_ERROR
, "No Value specified for the PCD %s." % (pcdname
))
398 (TokenSpaceGuidCName
, TokenCName
) = pcdname
.split('.')
402 TokenSpaceGuidCName
= ''
403 HasTokenSpace
= False
404 TokenSpaceGuidCNameList
= []
408 for package
in PGen
.PackageList
:
409 for key
in package
.Pcds
:
410 PcdItem
= package
.Pcds
[key
]
412 if (PcdItem
.TokenCName
, PcdItem
.TokenSpaceGuidCName
) == (TokenCName
, TokenSpaceGuidCName
):
413 PcdDatumType
= PcdItem
.DatumType
414 NewValue
= self
._BuildOptionPcdValueFormat
(TokenSpaceGuidCName
, TokenCName
, PcdDatumType
, pcdvalue
)
417 if PcdItem
.TokenCName
== TokenCName
:
418 if not PcdItem
.TokenSpaceGuidCName
in TokenSpaceGuidCNameList
:
419 if len (TokenSpaceGuidCNameList
) < 1:
420 TokenSpaceGuidCNameList
.append(PcdItem
.TokenSpaceGuidCName
)
421 PcdDatumType
= PcdItem
.DatumType
422 TokenSpaceGuidCName
= PcdItem
.TokenSpaceGuidCName
423 NewValue
= self
._BuildOptionPcdValueFormat
(TokenSpaceGuidCName
, TokenCName
, PcdDatumType
, pcdvalue
)
429 "The Pcd %s is found under multiple different TokenSpaceGuid: %s and %s." % (TokenCName
, PcdItem
.TokenSpaceGuidCName
, TokenSpaceGuidCNameList
[0])
432 GlobalData
.BuildOptionPcd
[i
] = (TokenSpaceGuidCName
, TokenCName
, NewValue
)
436 EdkLogger
.error('build', AUTOGEN_ERROR
, "The Pcd %s.%s is not found in the DEC file." % (TokenSpaceGuidCName
, TokenCName
))
438 EdkLogger
.error('build', AUTOGEN_ERROR
, "The Pcd %s is not found in the DEC file." % (TokenCName
))
440 for BuildData
in PGen
.BuildDatabase
._CACHE
_.values():
441 if BuildData
.Arch
!= Arch
:
443 if BuildData
.MetaFile
.Ext
== '.dec':
445 for key
in BuildData
.Pcds
:
446 PcdItem
= BuildData
.Pcds
[key
]
447 if (TokenSpaceGuidCName
, TokenCName
) == (PcdItem
.TokenSpaceGuidCName
, PcdItem
.TokenCName
):
448 PcdItem
.DefaultValue
= NewValue
450 if (TokenCName
, TokenSpaceGuidCName
) in PcdSet
:
451 PcdSet
[(TokenCName
, TokenSpaceGuidCName
)] = NewValue
453 SourcePcdDict
= {'DynamicEx':[], 'PatchableInModule':[],'Dynamic':[],'FixedAtBuild':[]}
454 BinaryPcdDict
= {'DynamicEx':[], 'PatchableInModule':[]}
455 SourcePcdDict_Keys
= SourcePcdDict
.keys()
456 BinaryPcdDict_Keys
= BinaryPcdDict
.keys()
458 # generate the SourcePcdDict and BinaryPcdDict
459 for BuildData
in PGen
.BuildDatabase
._CACHE
_.values():
460 if BuildData
.Arch
!= Arch
:
462 if BuildData
.MetaFile
.Ext
== '.inf':
463 for key
in BuildData
.Pcds
:
464 if BuildData
.Pcds
[key
].Pending
:
465 if key
in Platform
.Pcds
:
466 PcdInPlatform
= Platform
.Pcds
[key
]
467 if PcdInPlatform
.Type
not in [None, '']:
468 BuildData
.Pcds
[key
].Type
= PcdInPlatform
.Type
470 if BuildData
.MetaFile
in Platform
.Modules
:
471 PlatformModule
= Platform
.Modules
[str(BuildData
.MetaFile
)]
472 if key
in PlatformModule
.Pcds
:
473 PcdInPlatform
= PlatformModule
.Pcds
[key
]
474 if PcdInPlatform
.Type
not in [None, '']:
475 BuildData
.Pcds
[key
].Type
= PcdInPlatform
.Type
477 if 'DynamicEx' in BuildData
.Pcds
[key
].Type
:
478 if BuildData
.IsBinaryModule
:
479 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) not in BinaryPcdDict
['DynamicEx']:
480 BinaryPcdDict
['DynamicEx'].append((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
482 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) not in SourcePcdDict
['DynamicEx']:
483 SourcePcdDict
['DynamicEx'].append((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
485 elif 'PatchableInModule' in BuildData
.Pcds
[key
].Type
:
486 if BuildData
.MetaFile
.Ext
== '.inf':
487 if BuildData
.IsBinaryModule
:
488 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) not in BinaryPcdDict
['PatchableInModule']:
489 BinaryPcdDict
['PatchableInModule'].append((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
491 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) not in SourcePcdDict
['PatchableInModule']:
492 SourcePcdDict
['PatchableInModule'].append((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
494 elif 'Dynamic' in BuildData
.Pcds
[key
].Type
:
495 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) not in SourcePcdDict
['Dynamic']:
496 SourcePcdDict
['Dynamic'].append((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
497 elif 'FixedAtBuild' in BuildData
.Pcds
[key
].Type
:
498 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) not in SourcePcdDict
['FixedAtBuild']:
499 SourcePcdDict
['FixedAtBuild'].append((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
504 # intersection the BinaryPCD for Mixed PCD
506 for i
in BinaryPcdDict_Keys
:
507 for j
in BinaryPcdDict_Keys
:
509 IntersectionList
= list(set(BinaryPcdDict
[i
]).intersection(set(BinaryPcdDict
[j
])))
510 for item
in IntersectionList
:
511 NewPcd1
= (item
[0] + '_' + i
, item
[1])
512 NewPcd2
= (item
[0] + '_' + j
, item
[1])
513 if item
not in GlobalData
.MixedPcd
:
514 GlobalData
.MixedPcd
[item
] = [NewPcd1
, NewPcd2
]
516 if NewPcd1
not in GlobalData
.MixedPcd
[item
]:
517 GlobalData
.MixedPcd
[item
].append(NewPcd1
)
518 if NewPcd2
not in GlobalData
.MixedPcd
[item
]:
519 GlobalData
.MixedPcd
[item
].append(NewPcd2
)
524 # intersection the SourcePCD and BinaryPCD for Mixed PCD
526 for i
in SourcePcdDict_Keys
:
527 for j
in BinaryPcdDict_Keys
:
529 IntersectionList
= list(set(SourcePcdDict
[i
]).intersection(set(BinaryPcdDict
[j
])))
530 for item
in IntersectionList
:
531 NewPcd1
= (item
[0] + '_' + i
, item
[1])
532 NewPcd2
= (item
[0] + '_' + j
, item
[1])
533 if item
not in GlobalData
.MixedPcd
:
534 GlobalData
.MixedPcd
[item
] = [NewPcd1
, NewPcd2
]
536 if NewPcd1
not in GlobalData
.MixedPcd
[item
]:
537 GlobalData
.MixedPcd
[item
].append(NewPcd1
)
538 if NewPcd2
not in GlobalData
.MixedPcd
[item
]:
539 GlobalData
.MixedPcd
[item
].append(NewPcd2
)
543 for BuildData
in PGen
.BuildDatabase
._CACHE
_.values():
544 if BuildData
.Arch
!= Arch
:
546 for key
in BuildData
.Pcds
:
547 for SinglePcd
in GlobalData
.MixedPcd
:
548 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) == SinglePcd
:
549 for item
in GlobalData
.MixedPcd
[SinglePcd
]:
550 Pcd_Type
= item
[0].split('_')[-1]
551 if (Pcd_Type
== BuildData
.Pcds
[key
].Type
) or (Pcd_Type
== TAB_PCDS_DYNAMIC_EX
and BuildData
.Pcds
[key
].Type
in GenC
.gDynamicExPcd
) or \
552 (Pcd_Type
== TAB_PCDS_DYNAMIC
and BuildData
.Pcds
[key
].Type
in GenC
.gDynamicPcd
):
553 Value
= BuildData
.Pcds
[key
]
554 Value
.TokenCName
= BuildData
.Pcds
[key
].TokenCName
+ '_' + Pcd_Type
556 newkey
= (Value
.TokenCName
, key
[1])
558 newkey
= (Value
.TokenCName
, key
[1], key
[2])
559 del BuildData
.Pcds
[key
]
560 BuildData
.Pcds
[newkey
] = Value
568 # handle the mixed pcd in FDF file
570 if key
in GlobalData
.MixedPcd
:
573 for item
in GlobalData
.MixedPcd
[key
]:
576 #Collect package set information from INF of FDF
578 for Inf
in ModuleList
:
579 ModuleFile
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, Arch
)
580 if ModuleFile
in Platform
.Modules
:
582 ModuleData
= self
.BuildDatabase
[ModuleFile
, Arch
, Target
, Toolchain
]
583 PkgSet
.update(ModuleData
.Packages
)
584 Pkgs
= list(PkgSet
) + list(PGen
.PackageList
)
587 DecPcds
[Pcd
[0], Pcd
[1]] = Pkg
.Pcds
[Pcd
]
588 DecPcdsKey
.add((Pcd
[0], Pcd
[1], Pcd
[2]))
590 Platform
.SkuName
= self
.SkuId
591 for Name
, Guid
in PcdSet
:
592 if (Name
, Guid
) not in DecPcds
:
596 "PCD (%s.%s) used in FDF is not declared in DEC files." % (Guid
, Name
),
597 File
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
][0],
598 Line
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
][1]
601 # Check whether Dynamic or DynamicEx PCD used in FDF file. If used, build break and give a error message.
602 if (Name
, Guid
, TAB_PCDS_FIXED_AT_BUILD
) in DecPcdsKey \
603 or (Name
, Guid
, TAB_PCDS_PATCHABLE_IN_MODULE
) in DecPcdsKey \
604 or (Name
, Guid
, TAB_PCDS_FEATURE_FLAG
) in DecPcdsKey
:
605 Platform
.AddPcd(Name
, Guid
, PcdSet
[Name
, Guid
])
607 elif (Name
, Guid
, TAB_PCDS_DYNAMIC
) in DecPcdsKey
or (Name
, Guid
, TAB_PCDS_DYNAMIC_EX
) in DecPcdsKey
:
611 "Using Dynamic or DynamicEx type of PCD [%s.%s] in FDF file is not allowed." % (Guid
, Name
),
612 File
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
][0],
613 Line
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
][1]
616 Pa
= PlatformAutoGen(self
, self
.MetaFile
, Target
, Toolchain
, Arch
)
618 # Explicitly collect platform's dynamic PCDs
620 Pa
.CollectPlatformDynamicPcds()
621 Pa
.CollectFixedAtBuildPcds()
622 self
.AutoGenObjectList
.append(Pa
)
625 # Check PCDs token value conflict in each DEC file.
627 self
._CheckAllPcdsTokenValueConflict
()
630 # Check PCD type and definition between DSC and DEC
632 self
._CheckPcdDefineAndType
()
635 # self._CheckDuplicateInFV(Fdf)
637 self
._BuildDir
= None
639 self
._MakeFileDir
= None
640 self
._BuildCommand
= None
644 def _BuildOptionPcdValueFormat(self
, TokenSpaceGuidCName
, TokenCName
, PcdDatumType
, Value
):
645 if PcdDatumType
== 'VOID*':
646 if Value
.startswith('L'):
648 EdkLogger
.error('build', OPTION_VALUE_INVALID
, 'For Void* type PCD, when specify the Value in the command line, please use the following format: "string", L"string", B"{...}"')
649 Value
= Value
[0] + '"' + Value
[1:] + '"'
650 elif Value
.startswith('B'):
652 EdkLogger
.error('build', OPTION_VALUE_INVALID
, 'For Void* type PCD, when specify the Value in the command line, please use the following format: "string", L"string", B"{...}"')
656 EdkLogger
.error('build', OPTION_VALUE_INVALID
, 'For Void* type PCD, when specify the Value in the command line, please use the following format: "string", L"string", B"{...}"')
657 Value
= '"' + Value
+ '"'
659 IsValid
, Cause
= CheckPcdDatum(PcdDatumType
, Value
)
661 EdkLogger
.error('build', FORMAT_INVALID
, Cause
, ExtraData
="%s.%s" % (TokenSpaceGuidCName
, TokenCName
))
662 if PcdDatumType
== 'BOOLEAN':
663 Value
= Value
.upper()
664 if Value
== 'TRUE' or Value
== '1':
666 elif Value
== 'FALSE' or Value
== '0':
670 ## _CheckDuplicateInFV() method
672 # Check whether there is duplicate modules/files exist in FV section.
673 # The check base on the file GUID;
675 def _CheckDuplicateInFV(self
, Fdf
):
676 for Fv
in Fdf
.Profile
.FvDict
:
678 for FfsFile
in Fdf
.Profile
.FvDict
[Fv
].FfsList
:
679 if FfsFile
.InfFileName
and FfsFile
.NameGuid
== None:
684 for Pa
in self
.AutoGenObjectList
:
687 for Module
in Pa
.ModuleAutoGenList
:
688 if path
.normpath(Module
.MetaFile
.File
) == path
.normpath(FfsFile
.InfFileName
):
690 if not Module
.Guid
.upper() in _GuidDict
.keys():
691 _GuidDict
[Module
.Guid
.upper()] = FfsFile
694 EdkLogger
.error("build",
696 "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile
.CurrentLineNum
,
697 FfsFile
.CurrentLineContent
,
698 _GuidDict
[Module
.Guid
.upper()].CurrentLineNum
,
699 _GuidDict
[Module
.Guid
.upper()].CurrentLineContent
,
700 Module
.Guid
.upper()),
701 ExtraData
=self
.FdfFile
)
703 # Some INF files not have entity in DSC file.
706 if FfsFile
.InfFileName
.find('$') == -1:
707 InfPath
= NormPath(FfsFile
.InfFileName
)
708 if not os
.path
.exists(InfPath
):
709 EdkLogger
.error('build', GENFDS_ERROR
, "Non-existant Module %s !" % (FfsFile
.InfFileName
))
711 PathClassObj
= PathClass(FfsFile
.InfFileName
, self
.WorkspaceDir
)
713 # Here we just need to get FILE_GUID from INF file, use 'COMMON' as ARCH attribute. and use
714 # BuildObject from one of AutoGenObjectList is enough.
716 InfObj
= self
.AutoGenObjectList
[0].BuildDatabase
.WorkspaceDb
.BuildObject
[PathClassObj
, 'COMMON', self
.BuildTarget
, self
.ToolChain
]
717 if not InfObj
.Guid
.upper() in _GuidDict
.keys():
718 _GuidDict
[InfObj
.Guid
.upper()] = FfsFile
720 EdkLogger
.error("build",
722 "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile
.CurrentLineNum
,
723 FfsFile
.CurrentLineContent
,
724 _GuidDict
[InfObj
.Guid
.upper()].CurrentLineNum
,
725 _GuidDict
[InfObj
.Guid
.upper()].CurrentLineContent
,
726 InfObj
.Guid
.upper()),
727 ExtraData
=self
.FdfFile
)
730 if FfsFile
.NameGuid
!= None:
731 _CheckPCDAsGuidPattern
= re
.compile("^PCD\(.+\..+\)$")
734 # If the NameGuid reference a PCD name.
735 # The style must match: PCD(xxxx.yyy)
737 if _CheckPCDAsGuidPattern
.match(FfsFile
.NameGuid
):
739 # Replace the PCD value.
741 _PcdName
= FfsFile
.NameGuid
.lstrip("PCD(").rstrip(")")
743 for Pa
in self
.AutoGenObjectList
:
745 for PcdItem
in Pa
.AllPcdList
:
746 if (PcdItem
.TokenSpaceGuidCName
+ "." + PcdItem
.TokenCName
) == _PcdName
:
748 # First convert from CFormatGuid to GUID string
750 _PcdGuidString
= GuidStructureStringToGuidString(PcdItem
.DefaultValue
)
752 if not _PcdGuidString
:
754 # Then try Byte array.
756 _PcdGuidString
= GuidStructureByteArrayToGuidString(PcdItem
.DefaultValue
)
758 if not _PcdGuidString
:
760 # Not Byte array or CFormat GUID, raise error.
762 EdkLogger
.error("build",
764 "The format of PCD value is incorrect. PCD: %s , Value: %s\n" % (_PcdName
, PcdItem
.DefaultValue
),
765 ExtraData
=self
.FdfFile
)
767 if not _PcdGuidString
.upper() in _GuidDict
.keys():
768 _GuidDict
[_PcdGuidString
.upper()] = FfsFile
772 EdkLogger
.error("build",
774 "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile
.CurrentLineNum
,
775 FfsFile
.CurrentLineContent
,
776 _GuidDict
[_PcdGuidString
.upper()].CurrentLineNum
,
777 _GuidDict
[_PcdGuidString
.upper()].CurrentLineContent
,
778 FfsFile
.NameGuid
.upper()),
779 ExtraData
=self
.FdfFile
)
781 if not FfsFile
.NameGuid
.upper() in _GuidDict
.keys():
782 _GuidDict
[FfsFile
.NameGuid
.upper()] = FfsFile
785 # Two raw file GUID conflict.
787 EdkLogger
.error("build",
789 "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile
.CurrentLineNum
,
790 FfsFile
.CurrentLineContent
,
791 _GuidDict
[FfsFile
.NameGuid
.upper()].CurrentLineNum
,
792 _GuidDict
[FfsFile
.NameGuid
.upper()].CurrentLineContent
,
793 FfsFile
.NameGuid
.upper()),
794 ExtraData
=self
.FdfFile
)
797 def _CheckPcdDefineAndType(self
):
799 "FixedAtBuild", "PatchableInModule", "FeatureFlag",
800 "Dynamic", #"DynamicHii", "DynamicVpd",
801 "DynamicEx", # "DynamicExHii", "DynamicExVpd"
804 # This dict store PCDs which are not used by any modules with specified arches
806 for Pa
in self
.AutoGenObjectList
:
807 # Key of DSC's Pcds dictionary is PcdCName, TokenSpaceGuid
808 for Pcd
in Pa
.Platform
.Pcds
:
809 PcdType
= Pa
.Platform
.Pcds
[Pcd
].Type
811 # If no PCD type, this PCD comes from FDF
815 # Try to remove Hii and Vpd suffix
816 if PcdType
.startswith("DynamicEx"):
817 PcdType
= "DynamicEx"
818 elif PcdType
.startswith("Dynamic"):
821 for Package
in Pa
.PackageList
:
822 # Key of DEC's Pcds dictionary is PcdCName, TokenSpaceGuid, PcdType
823 if (Pcd
[0], Pcd
[1], PcdType
) in Package
.Pcds
:
825 for Type
in PcdTypeList
:
826 if (Pcd
[0], Pcd
[1], Type
) in Package
.Pcds
:
830 "Type [%s] of PCD [%s.%s] in DSC file doesn't match the type [%s] defined in DEC file." \
831 % (Pa
.Platform
.Pcds
[Pcd
].Type
, Pcd
[1], Pcd
[0], Type
),
836 UnusedPcd
.setdefault(Pcd
, []).append(Pa
.Arch
)
838 for Pcd
in UnusedPcd
:
841 "The PCD was not specified by any INF module in the platform for the given architecture.\n"
842 "\tPCD: [%s.%s]\n\tPlatform: [%s]\n\tArch: %s"
843 % (Pcd
[1], Pcd
[0], os
.path
.basename(str(self
.MetaFile
)), str(UnusedPcd
[Pcd
])),
848 return "%s [%s]" % (self
.MetaFile
, ", ".join(self
.ArchList
))
850 ## Return the directory to store FV files
852 if self
._FvDir
== None:
853 self
._FvDir
= path
.join(self
.BuildDir
, 'FV')
856 ## Return the directory to store all intermediate and final files built
857 def _GetBuildDir(self
):
858 return self
.AutoGenObjectList
[0].BuildDir
860 ## Return the build output directory platform specifies
861 def _GetOutputDir(self
):
862 return self
.Platform
.OutputDirectory
864 ## Return platform name
866 return self
.Platform
.PlatformName
868 ## Return meta-file GUID
870 return self
.Platform
.Guid
872 ## Return platform version
873 def _GetVersion(self
):
874 return self
.Platform
.Version
876 ## Return paths of tools
877 def _GetToolDefinition(self
):
878 return self
.AutoGenObjectList
[0].ToolDefinition
880 ## Return directory of platform makefile
882 # @retval string Makefile directory
884 def _GetMakeFileDir(self
):
885 if self
._MakeFileDir
== None:
886 self
._MakeFileDir
= self
.BuildDir
887 return self
._MakeFileDir
889 ## Return build command string
891 # @retval string Build command string
893 def _GetBuildCommand(self
):
894 if self
._BuildCommand
== None:
895 # BuildCommand should be all the same. So just get one from platform AutoGen
896 self
._BuildCommand
= self
.AutoGenObjectList
[0].BuildCommand
897 return self
._BuildCommand
899 ## Check the PCDs token value conflict in each DEC file.
901 # Will cause build break and raise error message while two PCDs conflict.
905 def _CheckAllPcdsTokenValueConflict(self
):
906 for Pa
in self
.AutoGenObjectList
:
907 for Package
in Pa
.PackageList
:
908 PcdList
= Package
.Pcds
.values()
909 PcdList
.sort(lambda x
, y
: cmp(int(x
.TokenValue
, 0), int(y
.TokenValue
, 0)))
911 while (Count
< len(PcdList
) - 1) :
912 Item
= PcdList
[Count
]
913 ItemNext
= PcdList
[Count
+ 1]
915 # Make sure in the same token space the TokenValue should be unique
917 if (int(Item
.TokenValue
, 0) == int(ItemNext
.TokenValue
, 0)):
918 SameTokenValuePcdList
= []
919 SameTokenValuePcdList
.append(Item
)
920 SameTokenValuePcdList
.append(ItemNext
)
921 RemainPcdListLength
= len(PcdList
) - Count
- 2
922 for ValueSameCount
in range(RemainPcdListLength
):
923 if int(PcdList
[len(PcdList
) - RemainPcdListLength
+ ValueSameCount
].TokenValue
, 0) == int(Item
.TokenValue
, 0):
924 SameTokenValuePcdList
.append(PcdList
[len(PcdList
) - RemainPcdListLength
+ ValueSameCount
])
928 # Sort same token value PCD list with TokenGuid and TokenCName
930 SameTokenValuePcdList
.sort(lambda x
, y
: cmp("%s.%s" % (x
.TokenSpaceGuidCName
, x
.TokenCName
), "%s.%s" % (y
.TokenSpaceGuidCName
, y
.TokenCName
)))
931 SameTokenValuePcdListCount
= 0
932 while (SameTokenValuePcdListCount
< len(SameTokenValuePcdList
) - 1):
934 TemListItem
= SameTokenValuePcdList
[SameTokenValuePcdListCount
]
935 TemListItemNext
= SameTokenValuePcdList
[SameTokenValuePcdListCount
+ 1]
937 if (TemListItem
.TokenSpaceGuidCName
== TemListItemNext
.TokenSpaceGuidCName
) and (TemListItem
.TokenCName
!= TemListItemNext
.TokenCName
):
938 for PcdItem
in GlobalData
.MixedPcd
:
939 if (TemListItem
.TokenCName
, TemListItem
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
] or \
940 (TemListItemNext
.TokenCName
, TemListItemNext
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
946 "The TokenValue [%s] of PCD [%s.%s] is conflict with: [%s.%s] in %s"\
947 % (TemListItem
.TokenValue
, TemListItem
.TokenSpaceGuidCName
, TemListItem
.TokenCName
, TemListItemNext
.TokenSpaceGuidCName
, TemListItemNext
.TokenCName
, Package
),
950 SameTokenValuePcdListCount
+= 1
951 Count
+= SameTokenValuePcdListCount
954 PcdList
= Package
.Pcds
.values()
955 PcdList
.sort(lambda x
, y
: cmp("%s.%s" % (x
.TokenSpaceGuidCName
, x
.TokenCName
), "%s.%s" % (y
.TokenSpaceGuidCName
, y
.TokenCName
)))
957 while (Count
< len(PcdList
) - 1) :
958 Item
= PcdList
[Count
]
959 ItemNext
= PcdList
[Count
+ 1]
961 # Check PCDs with same TokenSpaceGuidCName.TokenCName have same token value as well.
963 if (Item
.TokenSpaceGuidCName
== ItemNext
.TokenSpaceGuidCName
) and (Item
.TokenCName
== ItemNext
.TokenCName
) and (int(Item
.TokenValue
, 0) != int(ItemNext
.TokenValue
, 0)):
967 "The TokenValue [%s] of PCD [%s.%s] in %s defined in two places should be same as well."\
968 % (Item
.TokenValue
, Item
.TokenSpaceGuidCName
, Item
.TokenCName
, Package
),
972 ## Generate fds command
973 def _GenFdsCommand(self
):
974 return (GenMake
.TopLevelMakefile(self
)._TEMPLATE
_.Replace(GenMake
.TopLevelMakefile(self
)._TemplateDict
)).strip()
976 ## Create makefile for the platform and modules in it
978 # @param CreateDepsMakeFile Flag indicating if the makefile for
979 # modules will be created as well
981 def CreateMakeFile(self
, CreateDepsMakeFile
=False):
982 if CreateDepsMakeFile
:
983 for Pa
in self
.AutoGenObjectList
:
984 Pa
.CreateMakeFile(CreateDepsMakeFile
)
986 ## Create autogen code for platform and modules
988 # Since there's no autogen code for platform, this method will do nothing
989 # if CreateModuleCodeFile is set to False.
991 # @param CreateDepsCodeFile Flag indicating if creating module's
992 # autogen code file or not
994 def CreateCodeFile(self
, CreateDepsCodeFile
=False):
995 if not CreateDepsCodeFile
:
997 for Pa
in self
.AutoGenObjectList
:
998 Pa
.CreateCodeFile(CreateDepsCodeFile
)
1000 ## Create AsBuilt INF file the platform
1002 def CreateAsBuiltInf(self
):
1005 Name
= property(_GetName
)
1006 Guid
= property(_GetGuid
)
1007 Version
= property(_GetVersion
)
1008 OutputDir
= property(_GetOutputDir
)
1010 ToolDefinition
= property(_GetToolDefinition
) # toolcode : tool path
1012 BuildDir
= property(_GetBuildDir
)
1013 FvDir
= property(_GetFvDir
)
1014 MakeFileDir
= property(_GetMakeFileDir
)
1015 BuildCommand
= property(_GetBuildCommand
)
1016 GenFdsCommand
= property(_GenFdsCommand
)
1018 ## AutoGen class for platform
1020 # PlatformAutoGen class will process the original information in platform
1021 # file in order to generate makefile for platform.
1023 class PlatformAutoGen(AutoGen
):
1025 # Used to store all PCDs for both PEI and DXE phase, in order to generate
1026 # correct PCD database
1029 _NonDynaPcdList_
= []
1033 # The priority list while override build option
1035 PrioList
= {"0x11111" : 16, # TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE (Highest)
1036 "0x01111" : 15, # ******_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
1037 "0x10111" : 14, # TARGET_*********_ARCH_COMMANDTYPE_ATTRIBUTE
1038 "0x00111" : 13, # ******_*********_ARCH_COMMANDTYPE_ATTRIBUTE
1039 "0x11011" : 12, # TARGET_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE
1040 "0x01011" : 11, # ******_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE
1041 "0x10011" : 10, # TARGET_*********_****_COMMANDTYPE_ATTRIBUTE
1042 "0x00011" : 9, # ******_*********_****_COMMANDTYPE_ATTRIBUTE
1043 "0x11101" : 8, # TARGET_TOOLCHAIN_ARCH_***********_ATTRIBUTE
1044 "0x01101" : 7, # ******_TOOLCHAIN_ARCH_***********_ATTRIBUTE
1045 "0x10101" : 6, # TARGET_*********_ARCH_***********_ATTRIBUTE
1046 "0x00101" : 5, # ******_*********_ARCH_***********_ATTRIBUTE
1047 "0x11001" : 4, # TARGET_TOOLCHAIN_****_***********_ATTRIBUTE
1048 "0x01001" : 3, # ******_TOOLCHAIN_****_***********_ATTRIBUTE
1049 "0x10001" : 2, # TARGET_*********_****_***********_ATTRIBUTE
1050 "0x00001" : 1} # ******_*********_****_***********_ATTRIBUTE (Lowest)
1052 ## The real constructor of PlatformAutoGen
1054 # This method is not supposed to be called by users of PlatformAutoGen. It's
1055 # only used by factory method __new__() to do real initialization work for an
1056 # object of PlatformAutoGen
1058 # @param Workspace WorkspaceAutoGen object
1059 # @param PlatformFile Platform file (DSC file)
1060 # @param Target Build target (DEBUG, RELEASE)
1061 # @param Toolchain Name of tool chain
1062 # @param Arch arch of the platform supports
1064 def _Init(self
, Workspace
, PlatformFile
, Target
, Toolchain
, Arch
):
1065 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "AutoGen platform [%s] [%s]" % (PlatformFile
, Arch
))
1066 GlobalData
.gProcessingFile
= "%s [%s, %s, %s]" % (PlatformFile
, Arch
, Toolchain
, Target
)
1068 self
.MetaFile
= PlatformFile
1069 self
.Workspace
= Workspace
1070 self
.WorkspaceDir
= Workspace
.WorkspaceDir
1071 self
.ToolChain
= Toolchain
1072 self
.BuildTarget
= Target
1074 self
.SourceDir
= PlatformFile
.SubDir
1075 self
.SourceOverrideDir
= None
1076 self
.FdTargetList
= self
.Workspace
.FdTargetList
1077 self
.FvTargetList
= self
.Workspace
.FvTargetList
1078 self
.AllPcdList
= []
1079 # get the original module/package/platform objects
1080 self
.BuildDatabase
= Workspace
.BuildDatabase
1082 # flag indicating if the makefile/C-code file has been created or not
1083 self
.IsMakeFileCreated
= False
1084 self
.IsCodeFileCreated
= False
1086 self
._Platform
= None
1089 self
._Version
= None
1091 self
._BuildRule
= None
1092 self
._SourceDir
= None
1093 self
._BuildDir
= None
1094 self
._OutputDir
= None
1096 self
._MakeFileDir
= None
1097 self
._FdfFile
= None
1099 self
._PcdTokenNumber
= None # (TokenCName, TokenSpaceGuidCName) : GeneratedTokenNumber
1100 self
._DynamicPcdList
= None # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
1101 self
._NonDynamicPcdList
= None # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
1102 self
._NonDynamicPcdDict
= {}
1104 self
._ToolDefinitions
= None
1105 self
._ToolDefFile
= None # toolcode : tool path
1106 self
._ToolChainFamily
= None
1107 self
._BuildRuleFamily
= None
1108 self
._BuildOption
= None # toolcode : option
1109 self
._EdkBuildOption
= None # edktoolcode : option
1110 self
._EdkIIBuildOption
= None # edkiitoolcode : option
1111 self
._PackageList
= None
1112 self
._ModuleAutoGenList
= None
1113 self
._LibraryAutoGenList
= None
1114 self
._BuildCommand
= None
1115 self
._AsBuildInfList
= []
1116 self
._AsBuildModuleList
= []
1117 if GlobalData
.gFdfParser
!= None:
1118 self
._AsBuildInfList
= GlobalData
.gFdfParser
.Profile
.InfList
1119 for Inf
in self
._AsBuildInfList
:
1120 InfClass
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, self
.Arch
)
1121 M
= self
.BuildDatabase
[InfClass
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1122 if not M
.IsSupportedArch
:
1124 self
._AsBuildModuleList
.append(InfClass
)
1125 # get library/modules for build
1126 self
.LibraryBuildDirectoryList
= []
1127 self
.ModuleBuildDirectoryList
= []
1131 return "%s [%s]" % (self
.MetaFile
, self
.Arch
)
1133 ## Create autogen code for platform and modules
1135 # Since there's no autogen code for platform, this method will do nothing
1136 # if CreateModuleCodeFile is set to False.
1138 # @param CreateModuleCodeFile Flag indicating if creating module's
1139 # autogen code file or not
1141 def CreateCodeFile(self
, CreateModuleCodeFile
=False):
1142 # only module has code to be greated, so do nothing if CreateModuleCodeFile is False
1143 if self
.IsCodeFileCreated
or not CreateModuleCodeFile
:
1146 for Ma
in self
.ModuleAutoGenList
:
1147 Ma
.CreateCodeFile(True)
1149 # don't do this twice
1150 self
.IsCodeFileCreated
= True
1152 ## Generate Fds Command
1153 def _GenFdsCommand(self
):
1154 return self
.Workspace
.GenFdsCommand
1156 ## Create makefile for the platform and mdoules in it
1158 # @param CreateModuleMakeFile Flag indicating if the makefile for
1159 # modules will be created as well
1161 def CreateMakeFile(self
, CreateModuleMakeFile
=False):
1162 if CreateModuleMakeFile
:
1163 for ModuleFile
in self
.Platform
.Modules
:
1164 Ma
= ModuleAutoGen(self
.Workspace
, ModuleFile
, self
.BuildTarget
,
1165 self
.ToolChain
, self
.Arch
, self
.MetaFile
)
1166 Ma
.CreateMakeFile(True)
1167 #Ma.CreateAsBuiltInf()
1169 # no need to create makefile for the platform more than once
1170 if self
.IsMakeFileCreated
:
1173 # create library/module build dirs for platform
1174 Makefile
= GenMake
.PlatformMakefile(self
)
1175 self
.LibraryBuildDirectoryList
= Makefile
.GetLibraryBuildDirectoryList()
1176 self
.ModuleBuildDirectoryList
= Makefile
.GetModuleBuildDirectoryList()
1178 self
.IsMakeFileCreated
= True
1180 ## Deal with Shared FixedAtBuild Pcds
1182 def CollectFixedAtBuildPcds(self
):
1183 for LibAuto
in self
.LibraryAutoGenList
:
1184 FixedAtBuildPcds
= {}
1185 ShareFixedAtBuildPcdsSameValue
= {}
1186 for Module
in LibAuto
._ReferenceModules
:
1187 for Pcd
in Module
.FixedAtBuildPcds
+ LibAuto
.FixedAtBuildPcds
:
1188 key
= ".".join((Pcd
.TokenSpaceGuidCName
,Pcd
.TokenCName
))
1189 if key
not in FixedAtBuildPcds
:
1190 ShareFixedAtBuildPcdsSameValue
[key
] = True
1191 FixedAtBuildPcds
[key
] = Pcd
.DefaultValue
1193 if FixedAtBuildPcds
[key
] != Pcd
.DefaultValue
:
1194 ShareFixedAtBuildPcdsSameValue
[key
] = False
1195 for Pcd
in LibAuto
.FixedAtBuildPcds
:
1196 key
= ".".join((Pcd
.TokenSpaceGuidCName
,Pcd
.TokenCName
))
1197 if (Pcd
.TokenCName
,Pcd
.TokenSpaceGuidCName
) not in self
.NonDynamicPcdDict
:
1200 DscPcd
= self
.NonDynamicPcdDict
[(Pcd
.TokenCName
,Pcd
.TokenSpaceGuidCName
)]
1201 if DscPcd
.Type
!= "FixedAtBuild":
1203 if key
in ShareFixedAtBuildPcdsSameValue
and ShareFixedAtBuildPcdsSameValue
[key
]:
1204 LibAuto
.ConstPcd
[key
] = Pcd
.DefaultValue
1206 ## Collect dynamic PCDs
1208 # Gather dynamic PCDs list from each module and their settings from platform
1209 # This interface should be invoked explicitly when platform action is created.
1211 def CollectPlatformDynamicPcds(self
):
1212 # Override the platform Pcd's value by build option
1213 if GlobalData
.BuildOptionPcd
:
1214 for key
in self
.Platform
.Pcds
:
1215 PlatformPcd
= self
.Platform
.Pcds
[key
]
1216 for PcdItem
in GlobalData
.BuildOptionPcd
:
1217 if (PlatformPcd
.TokenSpaceGuidCName
, PlatformPcd
.TokenCName
) == (PcdItem
[0], PcdItem
[1]):
1218 PlatformPcd
.DefaultValue
= PcdItem
[2]
1219 if PlatformPcd
.SkuInfoList
:
1220 Sku
= PlatformPcd
.SkuInfoList
[PlatformPcd
.SkuInfoList
.keys()[0]]
1221 Sku
.DefaultValue
= PcdItem
[2]
1224 for key
in self
.Platform
.Pcds
:
1225 for SinglePcd
in GlobalData
.MixedPcd
:
1226 if (self
.Platform
.Pcds
[key
].TokenCName
, self
.Platform
.Pcds
[key
].TokenSpaceGuidCName
) == SinglePcd
:
1227 for item
in GlobalData
.MixedPcd
[SinglePcd
]:
1228 Pcd_Type
= item
[0].split('_')[-1]
1229 if (Pcd_Type
== self
.Platform
.Pcds
[key
].Type
) or (Pcd_Type
== TAB_PCDS_DYNAMIC_EX
and self
.Platform
.Pcds
[key
].Type
in GenC
.gDynamicExPcd
) or \
1230 (Pcd_Type
== TAB_PCDS_DYNAMIC
and self
.Platform
.Pcds
[key
].Type
in GenC
.gDynamicPcd
):
1231 Value
= self
.Platform
.Pcds
[key
]
1232 Value
.TokenCName
= self
.Platform
.Pcds
[key
].TokenCName
+ '_' + Pcd_Type
1234 newkey
= (Value
.TokenCName
, key
[1])
1236 newkey
= (Value
.TokenCName
, key
[1], key
[2])
1237 del self
.Platform
.Pcds
[key
]
1238 self
.Platform
.Pcds
[newkey
] = Value
1246 # for gathering error information
1247 NoDatumTypePcdList
= set()
1249 self
._GuidValue
= {}
1251 for InfName
in self
._AsBuildInfList
:
1252 InfName
= mws
.join(self
.WorkspaceDir
, InfName
)
1253 FdfModuleList
.append(os
.path
.normpath(InfName
))
1254 for F
in self
.Platform
.Modules
.keys():
1255 M
= ModuleAutoGen(self
.Workspace
, F
, self
.BuildTarget
, self
.ToolChain
, self
.Arch
, self
.MetaFile
)
1256 #GuidValue.update(M.Guids)
1258 self
.Platform
.Modules
[F
].M
= M
1260 for PcdFromModule
in M
.ModulePcdList
+ M
.LibraryPcdList
:
1261 # make sure that the "VOID*" kind of datum has MaxDatumSize set
1262 if PcdFromModule
.DatumType
== "VOID*" and PcdFromModule
.MaxDatumSize
in [None, '']:
1263 NoDatumTypePcdList
.add("%s.%s [%s]" % (PcdFromModule
.TokenSpaceGuidCName
, PcdFromModule
.TokenCName
, F
))
1265 # Check the PCD from Binary INF or Source INF
1266 if M
.IsBinaryModule
== True:
1267 PcdFromModule
.IsFromBinaryInf
= True
1269 # Check the PCD from DSC or not
1270 if (PcdFromModule
.TokenCName
, PcdFromModule
.TokenSpaceGuidCName
) in self
.Platform
.Pcds
.keys():
1271 PcdFromModule
.IsFromDsc
= True
1273 PcdFromModule
.IsFromDsc
= False
1274 if PcdFromModule
.Type
in GenC
.gDynamicPcd
or PcdFromModule
.Type
in GenC
.gDynamicExPcd
:
1275 if F
.Path
not in FdfModuleList
:
1276 # If one of the Source built modules listed in the DSC is not listed
1277 # in FDF modules, and the INF lists a PCD can only use the PcdsDynamic
1278 # access method (it is only listed in the DEC file that declares the
1279 # PCD as PcdsDynamic), then build tool will report warning message
1280 # notify the PI that they are attempting to build a module that must
1281 # be included in a flash image in order to be functional. These Dynamic
1282 # PCD will not be added into the Database unless it is used by other
1283 # modules that are included in the FDF file.
1284 if PcdFromModule
.Type
in GenC
.gDynamicPcd
and \
1285 PcdFromModule
.IsFromBinaryInf
== False:
1286 # Print warning message to let the developer make a determine.
1287 if PcdFromModule
not in PcdNotInDb
:
1288 PcdNotInDb
.append(PcdFromModule
)
1290 # If one of the Source built modules listed in the DSC is not listed in
1291 # FDF modules, and the INF lists a PCD can only use the PcdsDynamicEx
1292 # access method (it is only listed in the DEC file that declares the
1293 # PCD as PcdsDynamicEx), then DO NOT break the build; DO NOT add the
1294 # PCD to the Platform's PCD Database.
1295 if PcdFromModule
.Type
in GenC
.gDynamicExPcd
:
1296 if PcdFromModule
not in PcdNotInDb
:
1297 PcdNotInDb
.append(PcdFromModule
)
1300 # If a dynamic PCD used by a PEM module/PEI module & DXE module,
1301 # it should be stored in Pcd PEI database, If a dynamic only
1302 # used by DXE module, it should be stored in DXE PCD database.
1303 # The default Phase is DXE
1305 if M
.ModuleType
in ["PEIM", "PEI_CORE"]:
1306 PcdFromModule
.Phase
= "PEI"
1307 if PcdFromModule
not in self
._DynaPcdList
_:
1308 self
._DynaPcdList
_.append(PcdFromModule
)
1309 elif PcdFromModule
.Phase
== 'PEI':
1310 # overwrite any the same PCD existing, if Phase is PEI
1311 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1312 self
._DynaPcdList
_[Index
] = PcdFromModule
1313 elif PcdFromModule
not in self
._NonDynaPcdList
_:
1314 self
._NonDynaPcdList
_.append(PcdFromModule
)
1315 elif PcdFromModule
in self
._NonDynaPcdList
_ and PcdFromModule
.IsFromBinaryInf
== True:
1316 Index
= self
._NonDynaPcdList
_.index(PcdFromModule
)
1317 if self
._NonDynaPcdList
_[Index
].IsFromBinaryInf
== False:
1318 #The PCD from Binary INF will override the same one from source INF
1319 self
._NonDynaPcdList
_.remove (self
._NonDynaPcdList
_[Index
])
1320 PcdFromModule
.Pending
= False
1321 self
._NonDynaPcdList
_.append (PcdFromModule
)
1322 # Parse the DynamicEx PCD from the AsBuild INF module list of FDF.
1324 for ModuleInf
in self
.Platform
.Modules
.keys():
1325 DscModuleList
.append (os
.path
.normpath(ModuleInf
.Path
))
1326 # add the PCD from modules that listed in FDF but not in DSC to Database
1327 for InfName
in FdfModuleList
:
1328 if InfName
not in DscModuleList
:
1329 InfClass
= PathClass(InfName
)
1330 M
= self
.BuildDatabase
[InfClass
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1331 # If a module INF in FDF but not in current arch's DSC module list, it must be module (either binary or source)
1332 # for different Arch. PCDs in source module for different Arch is already added before, so skip the source module here.
1333 # For binary module, if in current arch, we need to list the PCDs into database.
1334 if not M
.IsSupportedArch
:
1336 # Override the module PCD setting by platform setting
1337 ModulePcdList
= self
.ApplyPcdSetting(M
, M
.Pcds
)
1338 for PcdFromModule
in ModulePcdList
:
1339 PcdFromModule
.IsFromBinaryInf
= True
1340 PcdFromModule
.IsFromDsc
= False
1341 # Only allow the DynamicEx and Patchable PCD in AsBuild INF
1342 if PcdFromModule
.Type
not in GenC
.gDynamicExPcd
and PcdFromModule
.Type
not in TAB_PCDS_PATCHABLE_IN_MODULE
:
1343 EdkLogger
.error("build", AUTOGEN_ERROR
, "PCD setting error",
1345 ExtraData
="\n\tExisted %s PCD %s in:\n\t\t%s\n"
1346 % (PcdFromModule
.Type
, PcdFromModule
.TokenCName
, InfName
))
1347 # make sure that the "VOID*" kind of datum has MaxDatumSize set
1348 if PcdFromModule
.DatumType
== "VOID*" and PcdFromModule
.MaxDatumSize
in [None, '']:
1349 NoDatumTypePcdList
.add("%s.%s [%s]" % (PcdFromModule
.TokenSpaceGuidCName
, PcdFromModule
.TokenCName
, InfName
))
1350 if M
.ModuleType
in ["PEIM", "PEI_CORE"]:
1351 PcdFromModule
.Phase
= "PEI"
1352 if PcdFromModule
not in self
._DynaPcdList
_ and PcdFromModule
.Type
in GenC
.gDynamicExPcd
:
1353 self
._DynaPcdList
_.append(PcdFromModule
)
1354 elif PcdFromModule
not in self
._NonDynaPcdList
_ and PcdFromModule
.Type
in TAB_PCDS_PATCHABLE_IN_MODULE
:
1355 self
._NonDynaPcdList
_.append(PcdFromModule
)
1356 if PcdFromModule
in self
._DynaPcdList
_ and PcdFromModule
.Phase
== 'PEI' and PcdFromModule
.Type
in GenC
.gDynamicExPcd
:
1357 # Overwrite the phase of any the same PCD existing, if Phase is PEI.
1358 # It is to solve the case that a dynamic PCD used by a PEM module/PEI
1359 # module & DXE module at a same time.
1360 # Overwrite the type of the PCDs in source INF by the type of AsBuild
1361 # INF file as DynamicEx.
1362 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1363 self
._DynaPcdList
_[Index
].Phase
= PcdFromModule
.Phase
1364 self
._DynaPcdList
_[Index
].Type
= PcdFromModule
.Type
1365 for PcdFromModule
in self
._NonDynaPcdList
_:
1366 # If a PCD is not listed in the DSC file, but binary INF files used by
1367 # this platform all (that use this PCD) list the PCD in a [PatchPcds]
1368 # section, AND all source INF files used by this platform the build
1369 # that use the PCD list the PCD in either a [Pcds] or [PatchPcds]
1370 # section, then the tools must NOT add the PCD to the Platform's PCD
1371 # Database; the build must assign the access method for this PCD as
1372 # PcdsPatchableInModule.
1373 if PcdFromModule
not in self
._DynaPcdList
_:
1375 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1376 if PcdFromModule
.IsFromDsc
== False and \
1377 PcdFromModule
.Type
in TAB_PCDS_PATCHABLE_IN_MODULE
and \
1378 PcdFromModule
.IsFromBinaryInf
== True and \
1379 self
._DynaPcdList
_[Index
].IsFromBinaryInf
== False:
1380 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1381 self
._DynaPcdList
_.remove (self
._DynaPcdList
_[Index
])
1383 # print out error information and break the build, if error found
1384 if len(NoDatumTypePcdList
) > 0:
1385 NoDatumTypePcdListString
= "\n\t\t".join(NoDatumTypePcdList
)
1386 EdkLogger
.error("build", AUTOGEN_ERROR
, "PCD setting error",
1388 ExtraData
="\n\tPCD(s) without MaxDatumSize:\n\t\t%s\n"
1389 % NoDatumTypePcdListString
)
1390 self
._NonDynamicPcdList
= self
._NonDynaPcdList
_
1391 self
._DynamicPcdList
= self
._DynaPcdList
_
1393 # Sort dynamic PCD list to:
1394 # 1) If PCD's datum type is VOID* and value is unicode string which starts with L, the PCD item should
1395 # try to be put header of dynamicd List
1396 # 2) If PCD is HII type, the PCD item should be put after unicode type PCD
1398 # The reason of sorting is make sure the unicode string is in double-byte alignment in string table.
1400 UnicodePcdArray
= []
1404 VpdFile
= VpdInfoFile
.VpdInfoFile()
1405 NeedProcessVpdMapFile
= False
1407 for pcd
in self
.Platform
.Pcds
.keys():
1408 if pcd
not in self
._PlatformPcds
.keys():
1409 self
._PlatformPcds
[pcd
] = self
.Platform
.Pcds
[pcd
]
1411 if (self
.Workspace
.ArchList
[-1] == self
.Arch
):
1412 for Pcd
in self
._DynamicPcdList
:
1413 # just pick the a value to determine whether is unicode string type
1414 Sku
= Pcd
.SkuInfoList
[Pcd
.SkuInfoList
.keys()[0]]
1415 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1417 PcdValue
= Sku
.DefaultValue
1418 if Pcd
.DatumType
== 'VOID*' and PcdValue
.startswith("L"):
1419 # if found PCD which datum value is unicode string the insert to left size of UnicodeIndex
1420 UnicodePcdArray
.append(Pcd
)
1421 elif len(Sku
.VariableName
) > 0:
1422 # if found HII type PCD then insert to right of UnicodeIndex
1423 HiiPcdArray
.append(Pcd
)
1425 OtherPcdArray
.append(Pcd
)
1426 if Pcd
.Type
in [TAB_PCDS_DYNAMIC_VPD
, TAB_PCDS_DYNAMIC_EX_VPD
]:
1427 VpdPcdDict
[(Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
)] = Pcd
1429 PlatformPcds
= self
._PlatformPcds
.keys()
1432 # Add VPD type PCD into VpdFile and determine whether the VPD PCD need to be fixed up.
1434 for PcdKey
in PlatformPcds
:
1435 Pcd
= self
._PlatformPcds
[PcdKey
]
1436 if Pcd
.Type
in [TAB_PCDS_DYNAMIC_VPD
, TAB_PCDS_DYNAMIC_EX_VPD
] and \
1437 PcdKey
in VpdPcdDict
:
1438 Pcd
= VpdPcdDict
[PcdKey
]
1439 for (SkuName
,Sku
) in Pcd
.SkuInfoList
.items():
1440 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1441 PcdValue
= Sku
.DefaultValue
1443 PcdValue
= Pcd
.DefaultValue
1444 if Sku
.VpdOffset
!= '*':
1445 if PcdValue
.startswith("{"):
1447 elif PcdValue
.startswith("L"):
1452 VpdOffset
= int(Sku
.VpdOffset
)
1455 VpdOffset
= int(Sku
.VpdOffset
, 16)
1457 EdkLogger
.error("build", FORMAT_INVALID
, "Invalid offset value %s for PCD %s.%s." % (Sku
.VpdOffset
, Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
))
1458 if VpdOffset
% Alignment
!= 0:
1459 if PcdValue
.startswith("{"):
1460 EdkLogger
.warn("build", "The offset value of PCD %s.%s is not 8-byte aligned!" %(Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
), File
=self
.MetaFile
)
1462 EdkLogger
.error("build", FORMAT_INVALID
, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
, Alignment
))
1463 VpdFile
.Add(Pcd
, Sku
.VpdOffset
)
1464 # if the offset of a VPD is *, then it need to be fixed up by third party tool.
1465 if not NeedProcessVpdMapFile
and Sku
.VpdOffset
== "*":
1466 NeedProcessVpdMapFile
= True
1467 if self
.Platform
.VpdToolGuid
== None or self
.Platform
.VpdToolGuid
== '':
1468 EdkLogger
.error("Build", FILE_NOT_FOUND
, \
1469 "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.")
1473 # Fix the PCDs define in VPD PCD section that never referenced by module.
1474 # An example is PCD for signature usage.
1476 for DscPcd
in PlatformPcds
:
1477 DscPcdEntry
= self
._PlatformPcds
[DscPcd
]
1478 if DscPcdEntry
.Type
in [TAB_PCDS_DYNAMIC_VPD
, TAB_PCDS_DYNAMIC_EX_VPD
]:
1479 if not (self
.Platform
.VpdToolGuid
== None or self
.Platform
.VpdToolGuid
== ''):
1481 for VpdPcd
in VpdFile
._VpdArray
.keys():
1482 # This PCD has been referenced by module
1483 if (VpdPcd
.TokenSpaceGuidCName
== DscPcdEntry
.TokenSpaceGuidCName
) and \
1484 (VpdPcd
.TokenCName
== DscPcdEntry
.TokenCName
):
1487 # Not found, it should be signature
1489 # just pick the a value to determine whether is unicode string type
1490 for (SkuName
,Sku
) in DscPcdEntry
.SkuInfoList
.items():
1491 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1493 # Need to iterate DEC pcd information to get the value & datumtype
1494 for eachDec
in self
.PackageList
:
1495 for DecPcd
in eachDec
.Pcds
:
1496 DecPcdEntry
= eachDec
.Pcds
[DecPcd
]
1497 if (DecPcdEntry
.TokenSpaceGuidCName
== DscPcdEntry
.TokenSpaceGuidCName
) and \
1498 (DecPcdEntry
.TokenCName
== DscPcdEntry
.TokenCName
):
1499 # Print warning message to let the developer make a determine.
1500 EdkLogger
.warn("build", "Unreferenced vpd pcd used!",
1501 File
=self
.MetaFile
, \
1502 ExtraData
= "PCD: %s.%s used in the DSC file %s is unreferenced." \
1503 %(DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
, self
.Platform
.MetaFile
.Path
))
1505 DscPcdEntry
.DatumType
= DecPcdEntry
.DatumType
1506 DscPcdEntry
.DefaultValue
= DecPcdEntry
.DefaultValue
1507 DscPcdEntry
.TokenValue
= DecPcdEntry
.TokenValue
1508 DscPcdEntry
.TokenSpaceGuidValue
= eachDec
.Guids
[DecPcdEntry
.TokenSpaceGuidCName
]
1509 # Only fix the value while no value provided in DSC file.
1510 if (Sku
.DefaultValue
== "" or Sku
.DefaultValue
==None):
1511 DscPcdEntry
.SkuInfoList
[DscPcdEntry
.SkuInfoList
.keys()[0]].DefaultValue
= DecPcdEntry
.DefaultValue
1513 if DscPcdEntry
not in self
._DynamicPcdList
:
1514 self
._DynamicPcdList
.append(DscPcdEntry
)
1515 # Sku = DscPcdEntry.SkuInfoList[DscPcdEntry.SkuInfoList.keys()[0]]
1516 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1517 PcdValue
= Sku
.DefaultValue
1519 PcdValue
= DscPcdEntry
.DefaultValue
1520 if Sku
.VpdOffset
!= '*':
1521 if PcdValue
.startswith("{"):
1523 elif PcdValue
.startswith("L"):
1528 VpdOffset
= int(Sku
.VpdOffset
)
1531 VpdOffset
= int(Sku
.VpdOffset
, 16)
1533 EdkLogger
.error("build", FORMAT_INVALID
, "Invalid offset value %s for PCD %s.%s." % (Sku
.VpdOffset
, DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
))
1534 if VpdOffset
% Alignment
!= 0:
1535 if PcdValue
.startswith("{"):
1536 EdkLogger
.warn("build", "The offset value of PCD %s.%s is not 8-byte aligned!" %(DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
), File
=self
.MetaFile
)
1538 EdkLogger
.error("build", FORMAT_INVALID
, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
, Alignment
))
1539 VpdFile
.Add(DscPcdEntry
, Sku
.VpdOffset
)
1540 if not NeedProcessVpdMapFile
and Sku
.VpdOffset
== "*":
1541 NeedProcessVpdMapFile
= True
1542 if DscPcdEntry
.DatumType
== 'VOID*' and PcdValue
.startswith("L"):
1543 UnicodePcdArray
.append(DscPcdEntry
)
1544 elif len(Sku
.VariableName
) > 0:
1545 HiiPcdArray
.append(DscPcdEntry
)
1547 OtherPcdArray
.append(DscPcdEntry
)
1549 # if the offset of a VPD is *, then it need to be fixed up by third party tool.
1553 if (self
.Platform
.FlashDefinition
== None or self
.Platform
.FlashDefinition
== '') and \
1554 VpdFile
.GetCount() != 0:
1555 EdkLogger
.error("build", ATTRIBUTE_NOT_AVAILABLE
,
1556 "Fail to get FLASH_DEFINITION definition in DSC file %s which is required when DSC contains VPD PCD." % str(self
.Platform
.MetaFile
))
1558 if VpdFile
.GetCount() != 0:
1559 FvPath
= os
.path
.join(self
.BuildDir
, "FV")
1560 if not os
.path
.exists(FvPath
):
1564 EdkLogger
.error("build", FILE_WRITE_FAILURE
, "Fail to create FV folder under %s" % self
.BuildDir
)
1566 VpdFilePath
= os
.path
.join(FvPath
, "%s.txt" % self
.Platform
.VpdToolGuid
)
1568 if VpdFile
.Write(VpdFilePath
):
1569 # retrieve BPDG tool's path from tool_def.txt according to VPD_TOOL_GUID defined in DSC file.
1571 for ToolDef
in self
.ToolDefinition
.values():
1572 if ToolDef
.has_key("GUID") and ToolDef
["GUID"] == self
.Platform
.VpdToolGuid
:
1573 if not ToolDef
.has_key("PATH"):
1574 EdkLogger
.error("build", ATTRIBUTE_NOT_AVAILABLE
, "PATH attribute was not provided for BPDG guid tool %s in tools_def.txt" % self
.Platform
.VpdToolGuid
)
1575 BPDGToolName
= ToolDef
["PATH"]
1577 # Call third party GUID BPDG tool.
1578 if BPDGToolName
!= None:
1579 VpdInfoFile
.CallExtenalBPDGTool(BPDGToolName
, VpdFilePath
)
1581 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.")
1583 # Process VPD map file generated by third party BPDG tool
1584 if NeedProcessVpdMapFile
:
1585 VpdMapFilePath
= os
.path
.join(self
.BuildDir
, "FV", "%s.map" % self
.Platform
.VpdToolGuid
)
1586 if os
.path
.exists(VpdMapFilePath
):
1587 VpdFile
.Read(VpdMapFilePath
)
1590 for Pcd
in self
._DynamicPcdList
:
1591 # just pick the a value to determine whether is unicode string type
1593 for (SkuName
,Sku
) in Pcd
.SkuInfoList
.items():
1594 if Sku
.VpdOffset
== "*":
1595 Sku
.VpdOffset
= VpdFile
.GetOffset(Pcd
)[i
].strip()
1598 EdkLogger
.error("build", FILE_READ_FAILURE
, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath
)
1600 # Delete the DynamicPcdList At the last time enter into this function
1601 del self
._DynamicPcdList
[:]
1602 self
._DynamicPcdList
.extend(UnicodePcdArray
)
1603 self
._DynamicPcdList
.extend(HiiPcdArray
)
1604 self
._DynamicPcdList
.extend(OtherPcdArray
)
1605 self
.AllPcdList
= self
._NonDynamicPcdList
+ self
._DynamicPcdList
1607 ## Return the platform build data object
1608 def _GetPlatform(self
):
1609 if self
._Platform
== None:
1610 self
._Platform
= self
.BuildDatabase
[self
.MetaFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1611 return self
._Platform
1613 ## Return platform name
1615 return self
.Platform
.PlatformName
1617 ## Return the meta file GUID
1619 return self
.Platform
.Guid
1621 ## Return the platform version
1622 def _GetVersion(self
):
1623 return self
.Platform
.Version
1625 ## Return the FDF file name
1626 def _GetFdfFile(self
):
1627 if self
._FdfFile
== None:
1628 if self
.Workspace
.FdfFile
!= "":
1629 self
._FdfFile
= mws
.join(self
.WorkspaceDir
, self
.Workspace
.FdfFile
)
1632 return self
._FdfFile
1634 ## Return the build output directory platform specifies
1635 def _GetOutputDir(self
):
1636 return self
.Platform
.OutputDirectory
1638 ## Return the directory to store all intermediate and final files built
1639 def _GetBuildDir(self
):
1640 if self
._BuildDir
== None:
1641 if os
.path
.isabs(self
.OutputDir
):
1642 self
._BuildDir
= path
.join(
1643 path
.abspath(self
.OutputDir
),
1644 self
.BuildTarget
+ "_" + self
.ToolChain
,
1647 self
._BuildDir
= path
.join(
1650 self
.BuildTarget
+ "_" + self
.ToolChain
,
1652 return self
._BuildDir
1654 ## Return directory of platform makefile
1656 # @retval string Makefile directory
1658 def _GetMakeFileDir(self
):
1659 if self
._MakeFileDir
== None:
1660 self
._MakeFileDir
= path
.join(self
.BuildDir
, self
.Arch
)
1661 return self
._MakeFileDir
1663 ## Return build command string
1665 # @retval string Build command string
1667 def _GetBuildCommand(self
):
1668 if self
._BuildCommand
== None:
1669 self
._BuildCommand
= []
1670 if "MAKE" in self
.ToolDefinition
and "PATH" in self
.ToolDefinition
["MAKE"]:
1671 self
._BuildCommand
+= SplitOption(self
.ToolDefinition
["MAKE"]["PATH"])
1672 if "FLAGS" in self
.ToolDefinition
["MAKE"]:
1673 NewOption
= self
.ToolDefinition
["MAKE"]["FLAGS"].strip()
1675 self
._BuildCommand
+= SplitOption(NewOption
)
1676 return self
._BuildCommand
1678 ## Get tool chain definition
1680 # Get each tool defition for given tool chain from tools_def.txt and platform
1682 def _GetToolDefinition(self
):
1683 if self
._ToolDefinitions
== None:
1684 ToolDefinition
= self
.Workspace
.ToolDef
.ToolsDefTxtDictionary
1685 if TAB_TOD_DEFINES_COMMAND_TYPE
not in self
.Workspace
.ToolDef
.ToolsDefTxtDatabase
:
1686 EdkLogger
.error('build', RESOURCE_NOT_AVAILABLE
, "No tools found in configuration",
1687 ExtraData
="[%s]" % self
.MetaFile
)
1688 self
._ToolDefinitions
= {}
1690 for Def
in ToolDefinition
:
1691 Target
, Tag
, Arch
, Tool
, Attr
= Def
.split("_")
1692 if Target
!= self
.BuildTarget
or Tag
!= self
.ToolChain
or Arch
!= self
.Arch
:
1695 Value
= ToolDefinition
[Def
]
1696 # don't record the DLL
1698 DllPathList
.add(Value
)
1701 if Tool
not in self
._ToolDefinitions
:
1702 self
._ToolDefinitions
[Tool
] = {}
1703 self
._ToolDefinitions
[Tool
][Attr
] = Value
1707 if GlobalData
.gOptions
.SilentMode
and "MAKE" in self
._ToolDefinitions
:
1708 if "FLAGS" not in self
._ToolDefinitions
["MAKE"]:
1709 self
._ToolDefinitions
["MAKE"]["FLAGS"] = ""
1710 self
._ToolDefinitions
["MAKE"]["FLAGS"] += " -s"
1712 for Tool
in self
._ToolDefinitions
:
1713 for Attr
in self
._ToolDefinitions
[Tool
]:
1714 Value
= self
._ToolDefinitions
[Tool
][Attr
]
1715 if Tool
in self
.BuildOption
and Attr
in self
.BuildOption
[Tool
]:
1716 # check if override is indicated
1717 if self
.BuildOption
[Tool
][Attr
].startswith('='):
1718 Value
= self
.BuildOption
[Tool
][Attr
][1:]
1720 Value
+= " " + self
.BuildOption
[Tool
][Attr
]
1723 # Don't put MAKE definition in the file
1727 ToolsDef
+= "%s = %s\n" % (Tool
, Value
)
1729 # Don't put MAKE definition in the file
1734 ToolsDef
+= "%s_%s = %s\n" % (Tool
, Attr
, Value
)
1737 SaveFileOnChange(self
.ToolDefinitionFile
, ToolsDef
)
1738 for DllPath
in DllPathList
:
1739 os
.environ
["PATH"] = DllPath
+ os
.pathsep
+ os
.environ
["PATH"]
1740 os
.environ
["MAKE_FLAGS"] = MakeFlags
1742 return self
._ToolDefinitions
1744 ## Return the paths of tools
1745 def _GetToolDefFile(self
):
1746 if self
._ToolDefFile
== None:
1747 self
._ToolDefFile
= os
.path
.join(self
.MakeFileDir
, "TOOLS_DEF." + self
.Arch
)
1748 return self
._ToolDefFile
1750 ## Retrieve the toolchain family of given toolchain tag. Default to 'MSFT'.
1751 def _GetToolChainFamily(self
):
1752 if self
._ToolChainFamily
== None:
1753 ToolDefinition
= self
.Workspace
.ToolDef
.ToolsDefTxtDatabase
1754 if TAB_TOD_DEFINES_FAMILY
not in ToolDefinition \
1755 or self
.ToolChain
not in ToolDefinition
[TAB_TOD_DEFINES_FAMILY
] \
1756 or not ToolDefinition
[TAB_TOD_DEFINES_FAMILY
][self
.ToolChain
]:
1757 EdkLogger
.verbose("No tool chain family found in configuration for %s. Default to MSFT." \
1759 self
._ToolChainFamily
= "MSFT"
1761 self
._ToolChainFamily
= ToolDefinition
[TAB_TOD_DEFINES_FAMILY
][self
.ToolChain
]
1762 return self
._ToolChainFamily
1764 def _GetBuildRuleFamily(self
):
1765 if self
._BuildRuleFamily
== None:
1766 ToolDefinition
= self
.Workspace
.ToolDef
.ToolsDefTxtDatabase
1767 if TAB_TOD_DEFINES_BUILDRULEFAMILY
not in ToolDefinition \
1768 or self
.ToolChain
not in ToolDefinition
[TAB_TOD_DEFINES_BUILDRULEFAMILY
] \
1769 or not ToolDefinition
[TAB_TOD_DEFINES_BUILDRULEFAMILY
][self
.ToolChain
]:
1770 EdkLogger
.verbose("No tool chain family found in configuration for %s. Default to MSFT." \
1772 self
._BuildRuleFamily
= "MSFT"
1774 self
._BuildRuleFamily
= ToolDefinition
[TAB_TOD_DEFINES_BUILDRULEFAMILY
][self
.ToolChain
]
1775 return self
._BuildRuleFamily
1777 ## Return the build options specific for all modules in this platform
1778 def _GetBuildOptions(self
):
1779 if self
._BuildOption
== None:
1780 self
._BuildOption
= self
._ExpandBuildOption
(self
.Platform
.BuildOptions
)
1781 return self
._BuildOption
1783 ## Return the build options specific for EDK modules in this platform
1784 def _GetEdkBuildOptions(self
):
1785 if self
._EdkBuildOption
== None:
1786 self
._EdkBuildOption
= self
._ExpandBuildOption
(self
.Platform
.BuildOptions
, EDK_NAME
)
1787 return self
._EdkBuildOption
1789 ## Return the build options specific for EDKII modules in this platform
1790 def _GetEdkIIBuildOptions(self
):
1791 if self
._EdkIIBuildOption
== None:
1792 self
._EdkIIBuildOption
= self
._ExpandBuildOption
(self
.Platform
.BuildOptions
, EDKII_NAME
)
1793 return self
._EdkIIBuildOption
1795 ## Parse build_rule.txt in Conf Directory.
1797 # @retval BuildRule object
1799 def _GetBuildRule(self
):
1800 if self
._BuildRule
== None:
1801 BuildRuleFile
= None
1802 if TAB_TAT_DEFINES_BUILD_RULE_CONF
in self
.Workspace
.TargetTxt
.TargetTxtDictionary
:
1803 BuildRuleFile
= self
.Workspace
.TargetTxt
.TargetTxtDictionary
[TAB_TAT_DEFINES_BUILD_RULE_CONF
]
1804 if BuildRuleFile
in [None, '']:
1805 BuildRuleFile
= gDefaultBuildRuleFile
1806 self
._BuildRule
= BuildRule(BuildRuleFile
)
1807 if self
._BuildRule
._FileVersion
== "":
1808 self
._BuildRule
._FileVersion
= AutoGenReqBuildRuleVerNum
1810 if self
._BuildRule
._FileVersion
< AutoGenReqBuildRuleVerNum
:
1811 # If Build Rule's version is less than the version number required by the tools, halting the build.
1812 EdkLogger
.error("build", AUTOGEN_ERROR
,
1813 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])"\
1814 % (self
._BuildRule
._FileVersion
, AutoGenReqBuildRuleVerNum
))
1816 return self
._BuildRule
1818 ## Summarize the packages used by modules in this platform
1819 def _GetPackageList(self
):
1820 if self
._PackageList
== None:
1821 self
._PackageList
= set()
1822 for La
in self
.LibraryAutoGenList
:
1823 self
._PackageList
.update(La
.DependentPackageList
)
1824 for Ma
in self
.ModuleAutoGenList
:
1825 self
._PackageList
.update(Ma
.DependentPackageList
)
1826 #Collect package set information from INF of FDF
1828 for ModuleFile
in self
._AsBuildModuleList
:
1829 if ModuleFile
in self
.Platform
.Modules
:
1831 ModuleData
= self
.BuildDatabase
[ModuleFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1832 PkgSet
.update(ModuleData
.Packages
)
1833 self
._PackageList
= list(self
._PackageList
) + list (PkgSet
)
1834 return self
._PackageList
1836 def _GetNonDynamicPcdDict(self
):
1837 if self
._NonDynamicPcdDict
:
1838 return self
._NonDynamicPcdDict
1839 for Pcd
in self
.NonDynamicPcdList
:
1840 self
._NonDynamicPcdDict
[(Pcd
.TokenCName
,Pcd
.TokenSpaceGuidCName
)] = Pcd
1841 return self
._NonDynamicPcdDict
1843 ## Get list of non-dynamic PCDs
1844 def _GetNonDynamicPcdList(self
):
1845 if self
._NonDynamicPcdList
== None:
1846 self
.CollectPlatformDynamicPcds()
1847 return self
._NonDynamicPcdList
1849 ## Get list of dynamic PCDs
1850 def _GetDynamicPcdList(self
):
1851 if self
._DynamicPcdList
== None:
1852 self
.CollectPlatformDynamicPcds()
1853 return self
._DynamicPcdList
1855 ## Generate Token Number for all PCD
1856 def _GetPcdTokenNumbers(self
):
1857 if self
._PcdTokenNumber
== None:
1858 self
._PcdTokenNumber
= sdict()
1861 # Make the Dynamic and DynamicEx PCD use within different TokenNumber area.
1865 # TokenNumber 0 ~ 10
1867 # TokeNumber 11 ~ 20
1869 for Pcd
in self
.DynamicPcdList
:
1870 if Pcd
.Phase
== "PEI":
1871 if Pcd
.Type
in ["Dynamic", "DynamicDefault", "DynamicVpd", "DynamicHii"]:
1872 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
1873 self
._PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
1876 for Pcd
in self
.DynamicPcdList
:
1877 if Pcd
.Phase
== "PEI":
1878 if Pcd
.Type
in ["DynamicEx", "DynamicExDefault", "DynamicExVpd", "DynamicExHii"]:
1879 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
1880 self
._PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
1883 for Pcd
in self
.DynamicPcdList
:
1884 if Pcd
.Phase
== "DXE":
1885 if Pcd
.Type
in ["Dynamic", "DynamicDefault", "DynamicVpd", "DynamicHii"]:
1886 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
1887 self
._PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
1890 for Pcd
in self
.DynamicPcdList
:
1891 if Pcd
.Phase
== "DXE":
1892 if Pcd
.Type
in ["DynamicEx", "DynamicExDefault", "DynamicExVpd", "DynamicExHii"]:
1893 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
1894 self
._PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
1897 for Pcd
in self
.NonDynamicPcdList
:
1898 self
._PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
1900 return self
._PcdTokenNumber
1902 ## Summarize ModuleAutoGen objects of all modules/libraries to be built for this platform
1903 def _GetAutoGenObjectList(self
):
1904 self
._ModuleAutoGenList
= []
1905 self
._LibraryAutoGenList
= []
1906 for ModuleFile
in self
.Platform
.Modules
:
1915 if Ma
not in self
._ModuleAutoGenList
:
1916 self
._ModuleAutoGenList
.append(Ma
)
1917 for La
in Ma
.LibraryAutoGenList
:
1918 if La
not in self
._LibraryAutoGenList
:
1919 self
._LibraryAutoGenList
.append(La
)
1920 if Ma
not in La
._ReferenceModules
:
1921 La
._ReferenceModules
.append(Ma
)
1923 ## Summarize ModuleAutoGen objects of all modules to be built for this platform
1924 def _GetModuleAutoGenList(self
):
1925 if self
._ModuleAutoGenList
== None:
1926 self
._GetAutoGenObjectList
()
1927 return self
._ModuleAutoGenList
1929 ## Summarize ModuleAutoGen objects of all libraries to be built for this platform
1930 def _GetLibraryAutoGenList(self
):
1931 if self
._LibraryAutoGenList
== None:
1932 self
._GetAutoGenObjectList
()
1933 return self
._LibraryAutoGenList
1935 ## Test if a module is supported by the platform
1937 # An error will be raised directly if the module or its arch is not supported
1938 # by the platform or current configuration
1940 def ValidModule(self
, Module
):
1941 return Module
in self
.Platform
.Modules
or Module
in self
.Platform
.LibraryInstances \
1942 or Module
in self
._AsBuildModuleList
1944 ## Resolve the library classes in a module to library instances
1946 # This method will not only resolve library classes but also sort the library
1947 # instances according to the dependency-ship.
1949 # @param Module The module from which the library classes will be resolved
1951 # @retval library_list List of library instances sorted
1953 def ApplyLibraryInstance(self
, Module
):
1954 # Cover the case that the binary INF file is list in the FDF file but not DSC file, return empty list directly
1955 if str(Module
) not in self
.Platform
.Modules
:
1958 ModuleType
= Module
.ModuleType
1960 # for overridding library instances with module specific setting
1961 PlatformModule
= self
.Platform
.Modules
[str(Module
)]
1963 # add forced library instances (specified under LibraryClasses sections)
1965 # If a module has a MODULE_TYPE of USER_DEFINED,
1966 # do not link in NULL library class instances from the global [LibraryClasses.*] sections.
1968 if Module
.ModuleType
!= SUP_MODULE_USER_DEFINED
:
1969 for LibraryClass
in self
.Platform
.LibraryClasses
.GetKeys():
1970 if LibraryClass
.startswith("NULL") and self
.Platform
.LibraryClasses
[LibraryClass
, Module
.ModuleType
]:
1971 Module
.LibraryClasses
[LibraryClass
] = self
.Platform
.LibraryClasses
[LibraryClass
, Module
.ModuleType
]
1973 # add forced library instances (specified in module overrides)
1974 for LibraryClass
in PlatformModule
.LibraryClasses
:
1975 if LibraryClass
.startswith("NULL"):
1976 Module
.LibraryClasses
[LibraryClass
] = PlatformModule
.LibraryClasses
[LibraryClass
]
1979 LibraryConsumerList
= [Module
]
1981 ConsumedByList
= sdict()
1982 LibraryInstance
= sdict()
1984 EdkLogger
.verbose("")
1985 EdkLogger
.verbose("Library instances of module [%s] [%s]:" % (str(Module
), self
.Arch
))
1986 while len(LibraryConsumerList
) > 0:
1987 M
= LibraryConsumerList
.pop()
1988 for LibraryClassName
in M
.LibraryClasses
:
1989 if LibraryClassName
not in LibraryInstance
:
1990 # override library instance for this module
1991 if LibraryClassName
in PlatformModule
.LibraryClasses
:
1992 LibraryPath
= PlatformModule
.LibraryClasses
[LibraryClassName
]
1994 LibraryPath
= self
.Platform
.LibraryClasses
[LibraryClassName
, ModuleType
]
1995 if LibraryPath
== None or LibraryPath
== "":
1996 LibraryPath
= M
.LibraryClasses
[LibraryClassName
]
1997 if LibraryPath
== None or LibraryPath
== "":
1998 EdkLogger
.error("build", RESOURCE_NOT_AVAILABLE
,
1999 "Instance of library class [%s] is not found" % LibraryClassName
,
2001 ExtraData
="in [%s] [%s]\n\tconsumed by module [%s]" % (str(M
), self
.Arch
, str(Module
)))
2003 LibraryModule
= self
.BuildDatabase
[LibraryPath
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
2004 # for those forced library instance (NULL library), add a fake library class
2005 if LibraryClassName
.startswith("NULL"):
2006 LibraryModule
.LibraryClass
.append(LibraryClassObject(LibraryClassName
, [ModuleType
]))
2007 elif LibraryModule
.LibraryClass
== None \
2008 or len(LibraryModule
.LibraryClass
) == 0 \
2009 or (ModuleType
!= 'USER_DEFINED'
2010 and ModuleType
not in LibraryModule
.LibraryClass
[0].SupModList
):
2011 # only USER_DEFINED can link against any library instance despite of its SupModList
2012 EdkLogger
.error("build", OPTION_MISSING
,
2013 "Module type [%s] is not supported by library instance [%s]" \
2014 % (ModuleType
, LibraryPath
), File
=self
.MetaFile
,
2015 ExtraData
="consumed by [%s]" % str(Module
))
2017 LibraryInstance
[LibraryClassName
] = LibraryModule
2018 LibraryConsumerList
.append(LibraryModule
)
2019 EdkLogger
.verbose("\t" + str(LibraryClassName
) + " : " + str(LibraryModule
))
2021 LibraryModule
= LibraryInstance
[LibraryClassName
]
2023 if LibraryModule
== None:
2026 if LibraryModule
.ConstructorList
!= [] and LibraryModule
not in Constructor
:
2027 Constructor
.append(LibraryModule
)
2029 if LibraryModule
not in ConsumedByList
:
2030 ConsumedByList
[LibraryModule
] = []
2031 # don't add current module itself to consumer list
2033 if M
in ConsumedByList
[LibraryModule
]:
2035 ConsumedByList
[LibraryModule
].append(M
)
2037 # Initialize the sorted output list to the empty set
2039 SortedLibraryList
= []
2041 # Q <- Set of all nodes with no incoming edges
2043 LibraryList
= [] #LibraryInstance.values()
2045 for LibraryClassName
in LibraryInstance
:
2046 M
= LibraryInstance
[LibraryClassName
]
2047 LibraryList
.append(M
)
2048 if ConsumedByList
[M
] == []:
2052 # start the DAG algorithm
2056 while Q
== [] and EdgeRemoved
:
2058 # for each node Item with a Constructor
2059 for Item
in LibraryList
:
2060 if Item
not in Constructor
:
2062 # for each Node without a constructor with an edge e from Item to Node
2063 for Node
in ConsumedByList
[Item
]:
2064 if Node
in Constructor
:
2066 # remove edge e from the graph if Node has no constructor
2067 ConsumedByList
[Item
].remove(Node
)
2069 if ConsumedByList
[Item
] == []:
2070 # insert Item into Q
2075 # DAG is done if there's no more incoming edge for all nodes
2079 # remove node from Q
2082 SortedLibraryList
.append(Node
)
2084 # for each node Item with an edge e from Node to Item do
2085 for Item
in LibraryList
:
2086 if Node
not in ConsumedByList
[Item
]:
2088 # remove edge e from the graph
2089 ConsumedByList
[Item
].remove(Node
)
2091 if ConsumedByList
[Item
] != []:
2093 # insert Item into Q, if Item has no other incoming edges
2097 # if any remaining node Item in the graph has a constructor and an incoming edge, then the graph has a cycle
2099 for Item
in LibraryList
:
2100 if ConsumedByList
[Item
] != [] and Item
in Constructor
and len(Constructor
) > 1:
2101 ErrorMessage
= "\tconsumed by " + "\n\tconsumed by ".join([str(L
) for L
in ConsumedByList
[Item
]])
2102 EdkLogger
.error("build", BUILD_ERROR
, 'Library [%s] with constructors has a cycle' % str(Item
),
2103 ExtraData
=ErrorMessage
, File
=self
.MetaFile
)
2104 if Item
not in SortedLibraryList
:
2105 SortedLibraryList
.append(Item
)
2108 # Build the list of constructor and destructir names
2109 # The DAG Topo sort produces the destructor order, so the list of constructors must generated in the reverse order
2111 SortedLibraryList
.reverse()
2112 return SortedLibraryList
2115 ## Override PCD setting (type, value, ...)
2117 # @param ToPcd The PCD to be overrided
2118 # @param FromPcd The PCD overrideing from
2120 def _OverridePcd(self
, ToPcd
, FromPcd
, Module
=""):
2122 # in case there's PCDs coming from FDF file, which have no type given.
2123 # at this point, ToPcd.Type has the type found from dependent
2126 TokenCName
= ToPcd
.TokenCName
2127 for PcdItem
in GlobalData
.MixedPcd
:
2128 if (ToPcd
.TokenCName
, ToPcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
2129 TokenCName
= PcdItem
[0]
2132 if GlobalData
.BuildOptionPcd
:
2133 for pcd
in GlobalData
.BuildOptionPcd
:
2134 if (FromPcd
.TokenSpaceGuidCName
, FromPcd
.TokenCName
) == (pcd
[0], pcd
[1]):
2135 FromPcd
.DefaultValue
= pcd
[2]
2137 if ToPcd
.Pending
and FromPcd
.Type
not in [None, '']:
2138 ToPcd
.Type
= FromPcd
.Type
2139 elif (ToPcd
.Type
not in [None, '']) and (FromPcd
.Type
not in [None, ''])\
2140 and (ToPcd
.Type
!= FromPcd
.Type
) and (ToPcd
.Type
in FromPcd
.Type
):
2141 if ToPcd
.Type
.strip() == "DynamicEx":
2142 ToPcd
.Type
= FromPcd
.Type
2143 elif ToPcd
.Type
not in [None, ''] and FromPcd
.Type
not in [None, ''] \
2144 and ToPcd
.Type
!= FromPcd
.Type
:
2145 EdkLogger
.error("build", OPTION_CONFLICT
, "Mismatched PCD type",
2146 ExtraData
="%s.%s is defined as [%s] in module %s, but as [%s] in platform."\
2147 % (ToPcd
.TokenSpaceGuidCName
, TokenCName
,
2148 ToPcd
.Type
, Module
, FromPcd
.Type
),
2151 if FromPcd
.MaxDatumSize
not in [None, '']:
2152 ToPcd
.MaxDatumSize
= FromPcd
.MaxDatumSize
2153 if FromPcd
.DefaultValue
not in [None, '']:
2154 ToPcd
.DefaultValue
= FromPcd
.DefaultValue
2155 if FromPcd
.TokenValue
not in [None, '']:
2156 ToPcd
.TokenValue
= FromPcd
.TokenValue
2157 if FromPcd
.MaxDatumSize
not in [None, '']:
2158 ToPcd
.MaxDatumSize
= FromPcd
.MaxDatumSize
2159 if FromPcd
.DatumType
not in [None, '']:
2160 ToPcd
.DatumType
= FromPcd
.DatumType
2161 if FromPcd
.SkuInfoList
not in [None, '', []]:
2162 ToPcd
.SkuInfoList
= FromPcd
.SkuInfoList
2164 # check the validation of datum
2165 IsValid
, Cause
= CheckPcdDatum(ToPcd
.DatumType
, ToPcd
.DefaultValue
)
2167 EdkLogger
.error('build', FORMAT_INVALID
, Cause
, File
=self
.MetaFile
,
2168 ExtraData
="%s.%s" % (ToPcd
.TokenSpaceGuidCName
, TokenCName
))
2169 ToPcd
.validateranges
= FromPcd
.validateranges
2170 ToPcd
.validlists
= FromPcd
.validlists
2171 ToPcd
.expressions
= FromPcd
.expressions
2173 if ToPcd
.DatumType
== "VOID*" and ToPcd
.MaxDatumSize
in ['', None]:
2174 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "No MaxDatumSize specified for PCD %s.%s" \
2175 % (ToPcd
.TokenSpaceGuidCName
, TokenCName
))
2176 Value
= ToPcd
.DefaultValue
2177 if Value
in [None, '']:
2178 ToPcd
.MaxDatumSize
= '1'
2179 elif Value
[0] == 'L':
2180 ToPcd
.MaxDatumSize
= str((len(Value
) - 2) * 2)
2181 elif Value
[0] == '{':
2182 ToPcd
.MaxDatumSize
= str(len(Value
.split(',')))
2184 ToPcd
.MaxDatumSize
= str(len(Value
) - 1)
2186 # apply default SKU for dynamic PCDS if specified one is not available
2187 if (ToPcd
.Type
in PCD_DYNAMIC_TYPE_LIST
or ToPcd
.Type
in PCD_DYNAMIC_EX_TYPE_LIST
) \
2188 and ToPcd
.SkuInfoList
in [None, {}, '']:
2189 if self
.Platform
.SkuName
in self
.Platform
.SkuIds
:
2190 SkuName
= self
.Platform
.SkuName
2193 ToPcd
.SkuInfoList
= {
2194 SkuName
: SkuInfoClass(SkuName
, self
.Platform
.SkuIds
[SkuName
], '', '', '', '', '', ToPcd
.DefaultValue
)
2197 ## Apply PCD setting defined platform to a module
2199 # @param Module The module from which the PCD setting will be overrided
2201 # @retval PCD_list The list PCDs with settings from platform
2203 def ApplyPcdSetting(self
, Module
, Pcds
):
2204 # for each PCD in module
2205 for Name
, Guid
in Pcds
:
2206 PcdInModule
= Pcds
[Name
, Guid
]
2207 # find out the PCD setting in platform
2208 if (Name
, Guid
) in self
.Platform
.Pcds
:
2209 PcdInPlatform
= self
.Platform
.Pcds
[Name
, Guid
]
2211 PcdInPlatform
= None
2212 # then override the settings if any
2213 self
._OverridePcd
(PcdInModule
, PcdInPlatform
, Module
)
2214 # resolve the VariableGuid value
2215 for SkuId
in PcdInModule
.SkuInfoList
:
2216 Sku
= PcdInModule
.SkuInfoList
[SkuId
]
2217 if Sku
.VariableGuid
== '': continue
2218 Sku
.VariableGuidValue
= GuidValue(Sku
.VariableGuid
, self
.PackageList
, self
.MetaFile
.Path
)
2219 if Sku
.VariableGuidValue
== None:
2220 PackageList
= "\n\t".join([str(P
) for P
in self
.PackageList
])
2223 RESOURCE_NOT_AVAILABLE
,
2224 "Value of GUID [%s] is not found in" % Sku
.VariableGuid
,
2225 ExtraData
=PackageList
+ "\n\t(used with %s.%s from module %s)" \
2226 % (Guid
, Name
, str(Module
)),
2230 # override PCD settings with module specific setting
2231 if Module
in self
.Platform
.Modules
:
2232 PlatformModule
= self
.Platform
.Modules
[str(Module
)]
2233 for Key
in PlatformModule
.Pcds
:
2235 self
._OverridePcd
(Pcds
[Key
], PlatformModule
.Pcds
[Key
], Module
)
2236 return Pcds
.values()
2238 ## Resolve library names to library modules
2240 # (for Edk.x modules)
2242 # @param Module The module from which the library names will be resolved
2244 # @retval library_list The list of library modules
2246 def ResolveLibraryReference(self
, Module
):
2247 EdkLogger
.verbose("")
2248 EdkLogger
.verbose("Library instances of module [%s] [%s]:" % (str(Module
), self
.Arch
))
2249 LibraryConsumerList
= [Module
]
2251 # "CompilerStub" is a must for Edk modules
2252 if Module
.Libraries
:
2253 Module
.Libraries
.append("CompilerStub")
2255 while len(LibraryConsumerList
) > 0:
2256 M
= LibraryConsumerList
.pop()
2257 for LibraryName
in M
.Libraries
:
2258 Library
= self
.Platform
.LibraryClasses
[LibraryName
, ':dummy:']
2260 for Key
in self
.Platform
.LibraryClasses
.data
.keys():
2261 if LibraryName
.upper() == Key
.upper():
2262 Library
= self
.Platform
.LibraryClasses
[Key
, ':dummy:']
2265 EdkLogger
.warn("build", "Library [%s] is not found" % LibraryName
, File
=str(M
),
2266 ExtraData
="\t%s [%s]" % (str(Module
), self
.Arch
))
2269 if Library
not in LibraryList
:
2270 LibraryList
.append(Library
)
2271 LibraryConsumerList
.append(Library
)
2272 EdkLogger
.verbose("\t" + LibraryName
+ " : " + str(Library
) + ' ' + str(type(Library
)))
2275 ## Calculate the priority value of the build option
2277 # @param Key Build option definition contain: TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
2279 # @retval Value Priority value based on the priority list.
2281 def CalculatePriorityValue(self
, Key
):
2282 Target
, ToolChain
, Arch
, CommandType
, Attr
= Key
.split('_')
2283 PriorityValue
= 0x11111
2285 PriorityValue
&= 0x01111
2286 if ToolChain
== "*":
2287 PriorityValue
&= 0x10111
2289 PriorityValue
&= 0x11011
2290 if CommandType
== "*":
2291 PriorityValue
&= 0x11101
2293 PriorityValue
&= 0x11110
2295 return self
.PrioList
["0x%0.5x" % PriorityValue
]
2298 ## Expand * in build option key
2300 # @param Options Options to be expanded
2302 # @retval options Options expanded
2304 def _ExpandBuildOption(self
, Options
, ModuleStyle
=None):
2311 # Construct a list contain the build options which need override.
2315 # Key[0] -- tool family
2316 # Key[1] -- TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
2318 if (Key
[0] == self
.BuildRuleFamily
and
2319 (ModuleStyle
== None or len(Key
) < 3 or (len(Key
) > 2 and Key
[2] == ModuleStyle
))):
2320 Target
, ToolChain
, Arch
, CommandType
, Attr
= Key
[1].split('_')
2321 if Target
== self
.BuildTarget
or Target
== "*":
2322 if ToolChain
== self
.ToolChain
or ToolChain
== "*":
2323 if Arch
== self
.Arch
or Arch
== "*":
2324 if Options
[Key
].startswith("="):
2325 if OverrideList
.get(Key
[1]) != None:
2326 OverrideList
.pop(Key
[1])
2327 OverrideList
[Key
[1]] = Options
[Key
]
2330 # Use the highest priority value.
2332 if (len(OverrideList
) >= 2):
2333 KeyList
= OverrideList
.keys()
2334 for Index
in range(len(KeyList
)):
2335 NowKey
= KeyList
[Index
]
2336 Target1
, ToolChain1
, Arch1
, CommandType1
, Attr1
= NowKey
.split("_")
2337 for Index1
in range(len(KeyList
) - Index
- 1):
2338 NextKey
= KeyList
[Index1
+ Index
+ 1]
2340 # Compare two Key, if one is included by another, choose the higher priority one
2342 Target2
, ToolChain2
, Arch2
, CommandType2
, Attr2
= NextKey
.split("_")
2343 if Target1
== Target2
or Target1
== "*" or Target2
== "*":
2344 if ToolChain1
== ToolChain2
or ToolChain1
== "*" or ToolChain2
== "*":
2345 if Arch1
== Arch2
or Arch1
== "*" or Arch2
== "*":
2346 if CommandType1
== CommandType2
or CommandType1
== "*" or CommandType2
== "*":
2347 if Attr1
== Attr2
or Attr1
== "*" or Attr2
== "*":
2348 if self
.CalculatePriorityValue(NowKey
) > self
.CalculatePriorityValue(NextKey
):
2349 if Options
.get((self
.BuildRuleFamily
, NextKey
)) != None:
2350 Options
.pop((self
.BuildRuleFamily
, NextKey
))
2352 if Options
.get((self
.BuildRuleFamily
, NowKey
)) != None:
2353 Options
.pop((self
.BuildRuleFamily
, NowKey
))
2356 if ModuleStyle
!= None and len (Key
) > 2:
2357 # Check Module style is EDK or EDKII.
2358 # Only append build option for the matched style module.
2359 if ModuleStyle
== EDK_NAME
and Key
[2] != EDK_NAME
:
2361 elif ModuleStyle
== EDKII_NAME
and Key
[2] != EDKII_NAME
:
2364 Target
, Tag
, Arch
, Tool
, Attr
= Key
[1].split("_")
2365 # if tool chain family doesn't match, skip it
2366 if Tool
in self
.ToolDefinition
and Family
!= "":
2367 FamilyIsNull
= False
2368 if self
.ToolDefinition
[Tool
].get(TAB_TOD_DEFINES_BUILDRULEFAMILY
, "") != "":
2369 if Family
!= self
.ToolDefinition
[Tool
][TAB_TOD_DEFINES_BUILDRULEFAMILY
]:
2371 elif Family
!= self
.ToolDefinition
[Tool
][TAB_TOD_DEFINES_FAMILY
]:
2374 # expand any wildcard
2375 if Target
== "*" or Target
== self
.BuildTarget
:
2376 if Tag
== "*" or Tag
== self
.ToolChain
:
2377 if Arch
== "*" or Arch
== self
.Arch
:
2378 if Tool
not in BuildOptions
:
2379 BuildOptions
[Tool
] = {}
2380 if Attr
!= "FLAGS" or Attr
not in BuildOptions
[Tool
] or Options
[Key
].startswith('='):
2381 BuildOptions
[Tool
][Attr
] = Options
[Key
]
2383 # append options for the same tool
2384 BuildOptions
[Tool
][Attr
] += " " + Options
[Key
]
2385 # Build Option Family has been checked, which need't to be checked again for family.
2386 if FamilyMatch
or FamilyIsNull
:
2390 if ModuleStyle
!= None and len (Key
) > 2:
2391 # Check Module style is EDK or EDKII.
2392 # Only append build option for the matched style module.
2393 if ModuleStyle
== EDK_NAME
and Key
[2] != EDK_NAME
:
2395 elif ModuleStyle
== EDKII_NAME
and Key
[2] != EDKII_NAME
:
2398 Target
, Tag
, Arch
, Tool
, Attr
= Key
[1].split("_")
2399 # if tool chain family doesn't match, skip it
2400 if Tool
not in self
.ToolDefinition
or Family
== "":
2402 # option has been added before
2403 if Family
!= self
.ToolDefinition
[Tool
][TAB_TOD_DEFINES_FAMILY
]:
2406 # expand any wildcard
2407 if Target
== "*" or Target
== self
.BuildTarget
:
2408 if Tag
== "*" or Tag
== self
.ToolChain
:
2409 if Arch
== "*" or Arch
== self
.Arch
:
2410 if Tool
not in BuildOptions
:
2411 BuildOptions
[Tool
] = {}
2412 if Attr
!= "FLAGS" or Attr
not in BuildOptions
[Tool
] or Options
[Key
].startswith('='):
2413 BuildOptions
[Tool
][Attr
] = Options
[Key
]
2415 # append options for the same tool
2416 BuildOptions
[Tool
][Attr
] += " " + Options
[Key
]
2419 ## Append build options in platform to a module
2421 # @param Module The module to which the build options will be appened
2423 # @retval options The options appended with build options in platform
2425 def ApplyBuildOption(self
, Module
):
2426 # Get the different options for the different style module
2427 if Module
.AutoGenVersion
< 0x00010005:
2428 PlatformOptions
= self
.EdkBuildOption
2429 ModuleTypeOptions
= self
.Platform
.GetBuildOptionsByModuleType(EDK_NAME
, Module
.ModuleType
)
2431 PlatformOptions
= self
.EdkIIBuildOption
2432 ModuleTypeOptions
= self
.Platform
.GetBuildOptionsByModuleType(EDKII_NAME
, Module
.ModuleType
)
2433 ModuleTypeOptions
= self
._ExpandBuildOption
(ModuleTypeOptions
)
2434 ModuleOptions
= self
._ExpandBuildOption
(Module
.BuildOptions
)
2435 if Module
in self
.Platform
.Modules
:
2436 PlatformModule
= self
.Platform
.Modules
[str(Module
)]
2437 PlatformModuleOptions
= self
._ExpandBuildOption
(PlatformModule
.BuildOptions
)
2439 PlatformModuleOptions
= {}
2441 BuildRuleOrder
= None
2442 for Options
in [self
.ToolDefinition
, ModuleOptions
, PlatformOptions
, ModuleTypeOptions
, PlatformModuleOptions
]:
2443 for Tool
in Options
:
2444 for Attr
in Options
[Tool
]:
2445 if Attr
== TAB_TOD_DEFINES_BUILDRULEORDER
:
2446 BuildRuleOrder
= Options
[Tool
][Attr
]
2448 AllTools
= set(ModuleOptions
.keys() + PlatformOptions
.keys() +
2449 PlatformModuleOptions
.keys() + ModuleTypeOptions
.keys() +
2450 self
.ToolDefinition
.keys())
2452 for Tool
in AllTools
:
2453 if Tool
not in BuildOptions
:
2454 BuildOptions
[Tool
] = {}
2456 for Options
in [self
.ToolDefinition
, ModuleOptions
, PlatformOptions
, ModuleTypeOptions
, PlatformModuleOptions
]:
2457 if Tool
not in Options
:
2459 for Attr
in Options
[Tool
]:
2460 Value
= Options
[Tool
][Attr
]
2462 # Do not generate it in Makefile
2464 if Attr
== TAB_TOD_DEFINES_BUILDRULEORDER
:
2466 if Attr
not in BuildOptions
[Tool
]:
2467 BuildOptions
[Tool
][Attr
] = ""
2468 # check if override is indicated
2469 if Value
.startswith('='):
2470 ToolPath
= Value
[1:]
2471 ToolPath
= mws
.handleWsMacro(ToolPath
)
2472 BuildOptions
[Tool
][Attr
] = ToolPath
2474 Value
= mws
.handleWsMacro(Value
)
2475 BuildOptions
[Tool
][Attr
] += " " + Value
2476 if Module
.AutoGenVersion
< 0x00010005 and self
.Workspace
.UniFlag
!= None:
2478 # Override UNI flag only for EDK module.
2480 if 'BUILD' not in BuildOptions
:
2481 BuildOptions
['BUILD'] = {}
2482 BuildOptions
['BUILD']['FLAGS'] = self
.Workspace
.UniFlag
2483 return BuildOptions
, BuildRuleOrder
2485 Platform
= property(_GetPlatform
)
2486 Name
= property(_GetName
)
2487 Guid
= property(_GetGuid
)
2488 Version
= property(_GetVersion
)
2490 OutputDir
= property(_GetOutputDir
)
2491 BuildDir
= property(_GetBuildDir
)
2492 MakeFileDir
= property(_GetMakeFileDir
)
2493 FdfFile
= property(_GetFdfFile
)
2495 PcdTokenNumber
= property(_GetPcdTokenNumbers
) # (TokenCName, TokenSpaceGuidCName) : GeneratedTokenNumber
2496 DynamicPcdList
= property(_GetDynamicPcdList
) # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
2497 NonDynamicPcdList
= property(_GetNonDynamicPcdList
) # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
2498 NonDynamicPcdDict
= property(_GetNonDynamicPcdDict
)
2499 PackageList
= property(_GetPackageList
)
2501 ToolDefinition
= property(_GetToolDefinition
) # toolcode : tool path
2502 ToolDefinitionFile
= property(_GetToolDefFile
) # toolcode : lib path
2503 ToolChainFamily
= property(_GetToolChainFamily
)
2504 BuildRuleFamily
= property(_GetBuildRuleFamily
)
2505 BuildOption
= property(_GetBuildOptions
) # toolcode : option
2506 EdkBuildOption
= property(_GetEdkBuildOptions
) # edktoolcode : option
2507 EdkIIBuildOption
= property(_GetEdkIIBuildOptions
) # edkiitoolcode : option
2509 BuildCommand
= property(_GetBuildCommand
)
2510 BuildRule
= property(_GetBuildRule
)
2511 ModuleAutoGenList
= property(_GetModuleAutoGenList
)
2512 LibraryAutoGenList
= property(_GetLibraryAutoGenList
)
2513 GenFdsCommand
= property(_GenFdsCommand
)
2515 ## ModuleAutoGen class
2517 # This class encapsules the AutoGen behaviors for the build tools. In addition to
2518 # the generation of AutoGen.h and AutoGen.c, it will generate *.depex file according
2519 # to the [depex] section in module's inf file.
2521 class ModuleAutoGen(AutoGen
):
2522 ## The real constructor of ModuleAutoGen
2524 # This method is not supposed to be called by users of ModuleAutoGen. It's
2525 # only used by factory method __new__() to do real initialization work for an
2526 # object of ModuleAutoGen
2528 # @param Workspace EdkIIWorkspaceBuild object
2529 # @param ModuleFile The path of module file
2530 # @param Target Build target (DEBUG, RELEASE)
2531 # @param Toolchain Name of tool chain
2532 # @param Arch The arch the module supports
2533 # @param PlatformFile Platform meta-file
2535 def _Init(self
, Workspace
, ModuleFile
, Target
, Toolchain
, Arch
, PlatformFile
):
2536 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "AutoGen module [%s] [%s]" % (ModuleFile
, Arch
))
2537 GlobalData
.gProcessingFile
= "%s [%s, %s, %s]" % (ModuleFile
, Arch
, Toolchain
, Target
)
2539 self
.Workspace
= Workspace
2540 self
.WorkspaceDir
= Workspace
.WorkspaceDir
2542 self
.MetaFile
= ModuleFile
2543 self
.PlatformInfo
= PlatformAutoGen(Workspace
, PlatformFile
, Target
, Toolchain
, Arch
)
2544 # check if this module is employed by active platform
2545 if not self
.PlatformInfo
.ValidModule(self
.MetaFile
):
2546 EdkLogger
.verbose("Module [%s] for [%s] is not employed by active platform\n" \
2547 % (self
.MetaFile
, Arch
))
2550 self
.SourceDir
= self
.MetaFile
.SubDir
2551 self
.SourceDir
= mws
.relpath(self
.SourceDir
, self
.WorkspaceDir
)
2553 self
.SourceOverrideDir
= None
2554 # use overrided path defined in DSC file
2555 if self
.MetaFile
.Key
in GlobalData
.gOverrideDir
:
2556 self
.SourceOverrideDir
= GlobalData
.gOverrideDir
[self
.MetaFile
.Key
]
2558 self
.ToolChain
= Toolchain
2559 self
.BuildTarget
= Target
2561 self
.ToolChainFamily
= self
.PlatformInfo
.ToolChainFamily
2562 self
.BuildRuleFamily
= self
.PlatformInfo
.BuildRuleFamily
2564 self
.IsMakeFileCreated
= False
2565 self
.IsCodeFileCreated
= False
2566 self
.IsAsBuiltInfCreated
= False
2567 self
.DepexGenerated
= False
2569 self
.BuildDatabase
= self
.Workspace
.BuildDatabase
2570 self
.BuildRuleOrder
= None
2575 self
._Version
= None
2576 self
._ModuleType
= None
2577 self
._ComponentType
= None
2578 self
._PcdIsDriver
= None
2579 self
._AutoGenVersion
= None
2580 self
._LibraryFlag
= None
2581 self
._CustomMakefile
= None
2584 self
._BuildDir
= None
2585 self
._OutputDir
= None
2586 self
._DebugDir
= None
2587 self
._MakeFileDir
= None
2589 self
._IncludePathList
= None
2590 self
._IncludePathLength
= 0
2591 self
._AutoGenFileList
= None
2592 self
._UnicodeFileList
= None
2593 self
._SourceFileList
= None
2594 self
._ObjectFileList
= None
2595 self
._BinaryFileList
= None
2597 self
._DependentPackageList
= None
2598 self
._DependentLibraryList
= None
2599 self
._LibraryAutoGenList
= None
2600 self
._DerivedPackageList
= None
2601 self
._ModulePcdList
= None
2602 self
._LibraryPcdList
= None
2603 self
._PcdComments
= sdict()
2604 self
._GuidList
= None
2605 self
._GuidsUsedByPcd
= None
2606 self
._GuidComments
= sdict()
2607 self
._ProtocolList
= None
2608 self
._ProtocolComments
= sdict()
2609 self
._PpiList
= None
2610 self
._PpiComments
= sdict()
2611 self
._DepexList
= None
2612 self
._DepexExpressionList
= None
2613 self
._BuildOption
= None
2614 self
._BuildOptionIncPathList
= None
2615 self
._BuildTargets
= None
2616 self
._IntroBuildTargetList
= None
2617 self
._FinalBuildTargetList
= None
2618 self
._FileTypes
= None
2619 self
._BuildRules
= None
2621 ## The Modules referenced to this Library
2622 # Only Library has this attribute
2623 self
._ReferenceModules
= []
2625 ## Store the FixedAtBuild Pcds
2627 self
._FixedAtBuildPcds
= []
2632 return "%s [%s]" % (self
.MetaFile
, self
.Arch
)
2634 # Get FixedAtBuild Pcds of this Module
2635 def _GetFixedAtBuildPcds(self
):
2636 if self
._FixedAtBuildPcds
:
2637 return self
._FixedAtBuildPcds
2638 for Pcd
in self
.ModulePcdList
:
2640 if not (Pcd
.Pending
== False and Pcd
.Type
== "FixedAtBuild"):
2642 elif Pcd
.Type
!= "FixedAtBuild":
2644 if Pcd
not in self
._FixedAtBuildPcds
:
2645 self
._FixedAtBuildPcds
.append(Pcd
)
2647 return self
._FixedAtBuildPcds
2649 def _GetUniqueBaseName(self
):
2650 BaseName
= self
.Name
2651 for Module
in self
.PlatformInfo
.ModuleAutoGenList
:
2652 if Module
.MetaFile
== self
.MetaFile
:
2654 if Module
.Name
== self
.Name
:
2655 if uuid
.UUID(Module
.Guid
) == uuid
.UUID(self
.Guid
):
2656 EdkLogger
.error("build", FILE_DUPLICATED
, 'Modules have same BaseName and FILE_GUID:\n'
2657 ' %s\n %s' % (Module
.MetaFile
, self
.MetaFile
))
2658 BaseName
= '%s_%s' % (self
.Name
, self
.Guid
)
2661 # Macros could be used in build_rule.txt (also Makefile)
2662 def _GetMacros(self
):
2663 if self
._Macro
== None:
2664 self
._Macro
= sdict()
2665 self
._Macro
["WORKSPACE" ] = self
.WorkspaceDir
2666 self
._Macro
["MODULE_NAME" ] = self
.Name
2667 self
._Macro
["MODULE_NAME_GUID" ] = self
._GetUniqueBaseName
()
2668 self
._Macro
["MODULE_GUID" ] = self
.Guid
2669 self
._Macro
["MODULE_VERSION" ] = self
.Version
2670 self
._Macro
["MODULE_TYPE" ] = self
.ModuleType
2671 self
._Macro
["MODULE_FILE" ] = str(self
.MetaFile
)
2672 self
._Macro
["MODULE_FILE_BASE_NAME" ] = self
.MetaFile
.BaseName
2673 self
._Macro
["MODULE_RELATIVE_DIR" ] = self
.SourceDir
2674 self
._Macro
["MODULE_DIR" ] = self
.SourceDir
2676 self
._Macro
["BASE_NAME" ] = self
.Name
2678 self
._Macro
["ARCH" ] = self
.Arch
2679 self
._Macro
["TOOLCHAIN" ] = self
.ToolChain
2680 self
._Macro
["TOOLCHAIN_TAG" ] = self
.ToolChain
2681 self
._Macro
["TOOL_CHAIN_TAG" ] = self
.ToolChain
2682 self
._Macro
["TARGET" ] = self
.BuildTarget
2684 self
._Macro
["BUILD_DIR" ] = self
.PlatformInfo
.BuildDir
2685 self
._Macro
["BIN_DIR" ] = os
.path
.join(self
.PlatformInfo
.BuildDir
, self
.Arch
)
2686 self
._Macro
["LIB_DIR" ] = os
.path
.join(self
.PlatformInfo
.BuildDir
, self
.Arch
)
2687 self
._Macro
["MODULE_BUILD_DIR" ] = self
.BuildDir
2688 self
._Macro
["OUTPUT_DIR" ] = self
.OutputDir
2689 self
._Macro
["DEBUG_DIR" ] = self
.DebugDir
2690 self
._Macro
["DEST_DIR_OUTPUT" ] = self
.OutputDir
2691 self
._Macro
["DEST_DIR_DEBUG" ] = self
.DebugDir
2692 self
._Macro
["PLATFORM_NAME" ] = self
.PlatformInfo
.Name
2693 self
._Macro
["PLATFORM_GUID" ] = self
.PlatformInfo
.Guid
2694 self
._Macro
["PLATFORM_VERSION" ] = self
.PlatformInfo
.Version
2695 self
._Macro
["PLATFORM_RELATIVE_DIR" ] = self
.PlatformInfo
.SourceDir
2696 self
._Macro
["PLATFORM_DIR" ] = mws
.join(self
.WorkspaceDir
, self
.PlatformInfo
.SourceDir
)
2697 self
._Macro
["PLATFORM_OUTPUT_DIR" ] = self
.PlatformInfo
.OutputDir
2700 ## Return the module build data object
2701 def _GetModule(self
):
2702 if self
._Module
== None:
2703 self
._Module
= self
.Workspace
.BuildDatabase
[self
.MetaFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
2706 ## Return the module name
2707 def _GetBaseName(self
):
2708 return self
.Module
.BaseName
2710 ## Return the module DxsFile if exist
2711 def _GetDxsFile(self
):
2712 return self
.Module
.DxsFile
2714 ## Return the module SourceOverridePath
2715 def _GetSourceOverridePath(self
):
2716 return self
.Module
.SourceOverridePath
2718 ## Return the module meta-file GUID
2721 # To build same module more than once, the module path with FILE_GUID overridden has
2722 # the file name FILE_GUIDmodule.inf, but the relative path (self.MetaFile.File) is the realy path
2723 # in DSC. The overridden GUID can be retrieved from file name
2725 if os
.path
.basename(self
.MetaFile
.File
) != os
.path
.basename(self
.MetaFile
.Path
):
2727 # Length of GUID is 36
2729 return os
.path
.basename(self
.MetaFile
.Path
)[:36]
2730 return self
.Module
.Guid
2732 ## Return the module version
2733 def _GetVersion(self
):
2734 return self
.Module
.Version
2736 ## Return the module type
2737 def _GetModuleType(self
):
2738 return self
.Module
.ModuleType
2740 ## Return the component type (for Edk.x style of module)
2741 def _GetComponentType(self
):
2742 return self
.Module
.ComponentType
2744 ## Return the build type
2745 def _GetBuildType(self
):
2746 return self
.Module
.BuildType
2748 ## Return the PCD_IS_DRIVER setting
2749 def _GetPcdIsDriver(self
):
2750 return self
.Module
.PcdIsDriver
2752 ## Return the autogen version, i.e. module meta-file version
2753 def _GetAutoGenVersion(self
):
2754 return self
.Module
.AutoGenVersion
2756 ## Check if the module is library or not
2757 def _IsLibrary(self
):
2758 if self
._LibraryFlag
== None:
2759 if self
.Module
.LibraryClass
!= None and self
.Module
.LibraryClass
!= []:
2760 self
._LibraryFlag
= True
2762 self
._LibraryFlag
= False
2763 return self
._LibraryFlag
2765 ## Check if the module is binary module or not
2766 def _IsBinaryModule(self
):
2767 return self
.Module
.IsBinaryModule
2769 ## Return the directory to store intermediate files of the module
2770 def _GetBuildDir(self
):
2771 if self
._BuildDir
== None:
2772 self
._BuildDir
= path
.join(
2773 self
.PlatformInfo
.BuildDir
,
2776 self
.MetaFile
.BaseName
2778 CreateDirectory(self
._BuildDir
)
2779 return self
._BuildDir
2781 ## Return the directory to store the intermediate object files of the mdoule
2782 def _GetOutputDir(self
):
2783 if self
._OutputDir
== None:
2784 self
._OutputDir
= path
.join(self
.BuildDir
, "OUTPUT")
2785 CreateDirectory(self
._OutputDir
)
2786 return self
._OutputDir
2788 ## Return the directory to store auto-gened source files of the mdoule
2789 def _GetDebugDir(self
):
2790 if self
._DebugDir
== None:
2791 self
._DebugDir
= path
.join(self
.BuildDir
, "DEBUG")
2792 CreateDirectory(self
._DebugDir
)
2793 return self
._DebugDir
2795 ## Return the path of custom file
2796 def _GetCustomMakefile(self
):
2797 if self
._CustomMakefile
== None:
2798 self
._CustomMakefile
= {}
2799 for Type
in self
.Module
.CustomMakefile
:
2800 if Type
in gMakeTypeMap
:
2801 MakeType
= gMakeTypeMap
[Type
]
2804 if self
.SourceOverrideDir
!= None:
2805 File
= os
.path
.join(self
.SourceOverrideDir
, self
.Module
.CustomMakefile
[Type
])
2806 if not os
.path
.exists(File
):
2807 File
= os
.path
.join(self
.SourceDir
, self
.Module
.CustomMakefile
[Type
])
2809 File
= os
.path
.join(self
.SourceDir
, self
.Module
.CustomMakefile
[Type
])
2810 self
._CustomMakefile
[MakeType
] = File
2811 return self
._CustomMakefile
2813 ## Return the directory of the makefile
2815 # @retval string The directory string of module's makefile
2817 def _GetMakeFileDir(self
):
2818 return self
.BuildDir
2820 ## Return build command string
2822 # @retval string Build command string
2824 def _GetBuildCommand(self
):
2825 return self
.PlatformInfo
.BuildCommand
2827 ## Get object list of all packages the module and its dependent libraries belong to
2829 # @retval list The list of package object
2831 def _GetDerivedPackageList(self
):
2833 for M
in [self
.Module
] + self
.DependentLibraryList
:
2834 for Package
in M
.Packages
:
2835 if Package
in PackageList
:
2837 PackageList
.append(Package
)
2840 ## Get the depex string
2842 # @return : a string contain all depex expresion.
2843 def _GetDepexExpresionString(self
):
2846 ## DPX_SOURCE IN Define section.
2847 if self
.Module
.DxsFile
:
2849 for M
in [self
.Module
] + self
.DependentLibraryList
:
2850 Filename
= M
.MetaFile
.Path
2851 InfObj
= InfSectionParser
.InfSectionParser(Filename
)
2852 DepexExpresionList
= InfObj
.GetDepexExpresionList()
2853 for DepexExpresion
in DepexExpresionList
:
2854 for key
in DepexExpresion
.keys():
2855 Arch
, ModuleType
= key
2856 DepexExpr
= [x
for x
in DepexExpresion
[key
] if not str(x
).startswith('#')]
2857 # the type of build module is USER_DEFINED.
2858 # All different DEPEX section tags would be copied into the As Built INF file
2859 # and there would be separate DEPEX section tags
2860 if self
.ModuleType
.upper() == SUP_MODULE_USER_DEFINED
:
2861 if (Arch
.upper() == self
.Arch
.upper()) and (ModuleType
.upper() != TAB_ARCH_COMMON
):
2862 DepexList
.append({(Arch
, ModuleType
): DepexExpr
})
2864 if Arch
.upper() == TAB_ARCH_COMMON
or \
2865 (Arch
.upper() == self
.Arch
.upper() and \
2866 ModuleType
.upper() in [TAB_ARCH_COMMON
, self
.ModuleType
.upper()]):
2867 DepexList
.append({(Arch
, ModuleType
): DepexExpr
})
2869 #the type of build module is USER_DEFINED.
2870 if self
.ModuleType
.upper() == SUP_MODULE_USER_DEFINED
:
2871 for Depex
in DepexList
:
2872 for key
in Depex
.keys():
2873 DepexStr
+= '[Depex.%s.%s]\n' % key
2874 DepexStr
+= '\n'.join(['# '+ val
for val
in Depex
[key
]])
2877 return '[Depex.%s]\n' % self
.Arch
2880 #the type of build module not is USER_DEFINED.
2882 for Depex
in DepexList
:
2887 for D
in Depex
.values():
2888 DepexStr
+= ' '.join([val
for val
in D
])
2889 Index
= DepexStr
.find('END')
2890 if Index
> -1 and Index
== len(DepexStr
) - 3:
2891 DepexStr
= DepexStr
[:-3]
2892 DepexStr
= DepexStr
.strip()
2895 DepexStr
= DepexStr
.lstrip('(').rstrip(')').strip()
2897 return '[Depex.%s]\n' % self
.Arch
2898 return '[Depex.%s]\n# ' % self
.Arch
+ DepexStr
2900 ## Merge dependency expression
2902 # @retval list The token list of the dependency expression after parsed
2904 def _GetDepexTokenList(self
):
2905 if self
._DepexList
== None:
2906 self
._DepexList
= {}
2907 if self
.DxsFile
or self
.IsLibrary
or TAB_DEPENDENCY_EXPRESSION_FILE
in self
.FileTypes
:
2908 return self
._DepexList
2910 self
._DepexList
[self
.ModuleType
] = []
2912 for ModuleType
in self
._DepexList
:
2913 DepexList
= self
._DepexList
[ModuleType
]
2915 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion
2917 for M
in [self
.Module
] + self
.DependentLibraryList
:
2919 for D
in M
.Depex
[self
.Arch
, ModuleType
]:
2921 DepexList
.append('AND')
2922 DepexList
.append('(')
2924 if DepexList
[-1] == 'END': # no need of a END at this time
2926 DepexList
.append(')')
2929 EdkLogger
.verbose("DEPEX[%s] (+%s) = %s" % (self
.Name
, M
.BaseName
, DepexList
))
2930 if 'BEFORE' in DepexList
or 'AFTER' in DepexList
:
2932 if len(DepexList
) > 0:
2933 EdkLogger
.verbose('')
2934 return self
._DepexList
2936 ## Merge dependency expression
2938 # @retval list The token list of the dependency expression after parsed
2940 def _GetDepexExpressionTokenList(self
):
2941 if self
._DepexExpressionList
== None:
2942 self
._DepexExpressionList
= {}
2943 if self
.DxsFile
or self
.IsLibrary
or TAB_DEPENDENCY_EXPRESSION_FILE
in self
.FileTypes
:
2944 return self
._DepexExpressionList
2946 self
._DepexExpressionList
[self
.ModuleType
] = ''
2948 for ModuleType
in self
._DepexExpressionList
:
2949 DepexExpressionList
= self
._DepexExpressionList
[ModuleType
]
2951 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion
2953 for M
in [self
.Module
] + self
.DependentLibraryList
:
2955 for D
in M
.DepexExpression
[self
.Arch
, ModuleType
]:
2956 if DepexExpressionList
!= '':
2957 DepexExpressionList
+= ' AND '
2958 DepexExpressionList
+= '('
2959 DepexExpressionList
+= D
2960 DepexExpressionList
= DepexExpressionList
.rstrip('END').strip()
2961 DepexExpressionList
+= ')'
2964 EdkLogger
.verbose("DEPEX[%s] (+%s) = %s" % (self
.Name
, M
.BaseName
, DepexExpressionList
))
2965 if 'BEFORE' in DepexExpressionList
or 'AFTER' in DepexExpressionList
:
2967 if len(DepexExpressionList
) > 0:
2968 EdkLogger
.verbose('')
2969 self
._DepexExpressionList
[ModuleType
] = DepexExpressionList
2970 return self
._DepexExpressionList
2972 ## Return the list of specification version required for the module
2974 # @retval list The list of specification defined in module file
2976 def _GetSpecification(self
):
2977 return self
.Module
.Specification
2979 ## Tool option for the module build
2981 # @param PlatformInfo The object of PlatformBuildInfo
2982 # @retval dict The dict containing valid options
2984 def _GetModuleBuildOption(self
):
2985 if self
._BuildOption
== None:
2986 self
._BuildOption
, self
.BuildRuleOrder
= self
.PlatformInfo
.ApplyBuildOption(self
.Module
)
2987 if self
.BuildRuleOrder
:
2988 self
.BuildRuleOrder
= ['.%s' % Ext
for Ext
in self
.BuildRuleOrder
.split()]
2989 return self
._BuildOption
2991 ## Get include path list from tool option for the module build
2993 # @retval list The include path list
2995 def _GetBuildOptionIncPathList(self
):
2996 if self
._BuildOptionIncPathList
== None:
2998 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT
2999 # is the former use /I , the Latter used -I to specify include directories
3001 if self
.PlatformInfo
.ToolChainFamily
in ('MSFT'):
3002 gBuildOptIncludePattern
= re
.compile(r
"(?:.*?)/I[ \t]*([^ ]*)", re
.MULTILINE | re
.DOTALL
)
3003 elif self
.PlatformInfo
.ToolChainFamily
in ('INTEL', 'GCC', 'RVCT'):
3004 gBuildOptIncludePattern
= re
.compile(r
"(?:.*?)-I[ \t]*([^ ]*)", re
.MULTILINE | re
.DOTALL
)
3007 # New ToolChainFamily, don't known whether there is option to specify include directories
3009 self
._BuildOptionIncPathList
= []
3010 return self
._BuildOptionIncPathList
3012 BuildOptionIncPathList
= []
3013 for Tool
in ('CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'ASM'):
3016 FlagOption
= self
.BuildOption
[Tool
][Attr
]
3020 if self
.PlatformInfo
.ToolChainFamily
!= 'RVCT':
3021 IncPathList
= [NormPath(Path
, self
.Macros
) for Path
in gBuildOptIncludePattern
.findall(FlagOption
)]
3024 # RVCT may specify a list of directory seperated by commas
3027 for Path
in gBuildOptIncludePattern
.findall(FlagOption
):
3028 PathList
= GetSplitList(Path
, TAB_COMMA_SPLIT
)
3029 IncPathList
+= [NormPath(PathEntry
, self
.Macros
) for PathEntry
in PathList
]
3032 # EDK II modules must not reference header files outside of the packages they depend on or
3033 # within the module's directory tree. Report error if violation.
3035 if self
.AutoGenVersion
>= 0x00010005 and len(IncPathList
) > 0:
3036 for Path
in IncPathList
:
3037 if (Path
not in self
.IncludePathList
) and (CommonPath([Path
, self
.MetaFile
.Dir
]) != self
.MetaFile
.Dir
):
3038 ErrMsg
= "The include directory for the EDK II module in this line is invalid %s specified in %s FLAGS '%s'" % (Path
, Tool
, FlagOption
)
3039 EdkLogger
.error("build",
3042 File
=str(self
.MetaFile
))
3045 BuildOptionIncPathList
+= IncPathList
3047 self
._BuildOptionIncPathList
= BuildOptionIncPathList
3049 return self
._BuildOptionIncPathList
3051 ## Return a list of files which can be built from source
3053 # What kind of files can be built is determined by build rules in
3054 # $(CONF_DIRECTORY)/build_rule.txt and toolchain family.
3056 def _GetSourceFileList(self
):
3057 if self
._SourceFileList
== None:
3058 self
._SourceFileList
= []
3059 for F
in self
.Module
.Sources
:
3061 if F
.TagName
not in ("", "*", self
.ToolChain
):
3062 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "The toolchain [%s] for processing file [%s] is found, "
3063 "but [%s] is needed" % (F
.TagName
, str(F
), self
.ToolChain
))
3065 # match tool chain family
3066 if F
.ToolChainFamily
not in ("", "*", self
.ToolChainFamily
):
3069 "The file [%s] must be built by tools of [%s], " \
3070 "but current toolchain family is [%s]" \
3071 % (str(F
), F
.ToolChainFamily
, self
.ToolChainFamily
))
3074 # add the file path into search path list for file including
3075 if F
.Dir
not in self
.IncludePathList
and self
.AutoGenVersion
>= 0x00010005:
3076 self
.IncludePathList
.insert(0, F
.Dir
)
3077 self
._SourceFileList
.append(F
)
3079 self
._MatchBuildRuleOrder
(self
._SourceFileList
)
3081 for F
in self
._SourceFileList
:
3082 self
._ApplyBuildRule
(F
, TAB_UNKNOWN_FILE
)
3083 return self
._SourceFileList
3085 def _MatchBuildRuleOrder(self
, FileList
):
3087 self
._GetModuleBuildOption
()
3088 for SingleFile
in FileList
:
3089 if self
.BuildRuleOrder
and SingleFile
.Ext
in self
.BuildRuleOrder
and SingleFile
.Ext
in self
.BuildRules
:
3090 key
= SingleFile
.Path
.split(SingleFile
.Ext
)[0]
3091 if key
in Order_Dict
:
3092 Order_Dict
[key
].append(SingleFile
.Ext
)
3094 Order_Dict
[key
] = [SingleFile
.Ext
]
3097 for F
in Order_Dict
:
3098 if len(Order_Dict
[F
]) > 1:
3099 Order_Dict
[F
].sort(key
=lambda i
: self
.BuildRuleOrder
.index(i
))
3100 for Ext
in Order_Dict
[F
][1:]:
3101 RemoveList
.append(F
+ Ext
)
3103 for item
in RemoveList
:
3104 FileList
.remove(item
)
3108 ## Return the list of unicode files
3109 def _GetUnicodeFileList(self
):
3110 if self
._UnicodeFileList
== None:
3111 if TAB_UNICODE_FILE
in self
.FileTypes
:
3112 self
._UnicodeFileList
= self
.FileTypes
[TAB_UNICODE_FILE
]
3114 self
._UnicodeFileList
= []
3115 return self
._UnicodeFileList
3117 ## Return a list of files which can be built from binary
3119 # "Build" binary files are just to copy them to build directory.
3121 # @retval list The list of files which can be built later
3123 def _GetBinaryFiles(self
):
3124 if self
._BinaryFileList
== None:
3125 self
._BinaryFileList
= []
3126 for F
in self
.Module
.Binaries
:
3127 if F
.Target
not in ['COMMON', '*'] and F
.Target
!= self
.BuildTarget
:
3129 self
._BinaryFileList
.append(F
)
3130 self
._ApplyBuildRule
(F
, F
.Type
)
3131 return self
._BinaryFileList
3133 def _GetBuildRules(self
):
3134 if self
._BuildRules
== None:
3136 BuildRuleDatabase
= self
.PlatformInfo
.BuildRule
3137 for Type
in BuildRuleDatabase
.FileTypeList
:
3138 #first try getting build rule by BuildRuleFamily
3139 RuleObject
= BuildRuleDatabase
[Type
, self
.BuildType
, self
.Arch
, self
.BuildRuleFamily
]
3141 # build type is always module type, but ...
3142 if self
.ModuleType
!= self
.BuildType
:
3143 RuleObject
= BuildRuleDatabase
[Type
, self
.ModuleType
, self
.Arch
, self
.BuildRuleFamily
]
3144 #second try getting build rule by ToolChainFamily
3146 RuleObject
= BuildRuleDatabase
[Type
, self
.BuildType
, self
.Arch
, self
.ToolChainFamily
]
3148 # build type is always module type, but ...
3149 if self
.ModuleType
!= self
.BuildType
:
3150 RuleObject
= BuildRuleDatabase
[Type
, self
.ModuleType
, self
.Arch
, self
.ToolChainFamily
]
3153 RuleObject
= RuleObject
.Instantiate(self
.Macros
)
3154 BuildRules
[Type
] = RuleObject
3155 for Ext
in RuleObject
.SourceFileExtList
:
3156 BuildRules
[Ext
] = RuleObject
3157 self
._BuildRules
= BuildRules
3158 return self
._BuildRules
3160 def _ApplyBuildRule(self
, File
, FileType
):
3161 if self
._BuildTargets
== None:
3162 self
._IntroBuildTargetList
= set()
3163 self
._FinalBuildTargetList
= set()
3164 self
._BuildTargets
= {}
3165 self
._FileTypes
= {}
3167 SubDirectory
= os
.path
.join(self
.OutputDir
, File
.SubDir
)
3168 if not os
.path
.exists(SubDirectory
):
3169 CreateDirectory(SubDirectory
)
3175 # Make sure to get build rule order value
3177 self
._GetModuleBuildOption
()
3179 while Index
< len(SourceList
):
3180 Source
= SourceList
[Index
]
3184 CreateDirectory(Source
.Dir
)
3186 if File
.IsBinary
and File
== Source
and self
._BinaryFileList
!= None and File
in self
._BinaryFileList
:
3187 # Skip all files that are not binary libraries
3188 if not self
.IsLibrary
:
3190 RuleObject
= self
.BuildRules
[TAB_DEFAULT_BINARY_FILE
]
3191 elif FileType
in self
.BuildRules
:
3192 RuleObject
= self
.BuildRules
[FileType
]
3193 elif Source
.Ext
in self
.BuildRules
:
3194 RuleObject
= self
.BuildRules
[Source
.Ext
]
3196 # stop at no more rules
3198 self
._FinalBuildTargetList
.add(LastTarget
)
3201 FileType
= RuleObject
.SourceFileType
3202 if FileType
not in self
._FileTypes
:
3203 self
._FileTypes
[FileType
] = set()
3204 self
._FileTypes
[FileType
].add(Source
)
3206 # stop at STATIC_LIBRARY for library
3207 if self
.IsLibrary
and FileType
== TAB_STATIC_LIBRARY
:
3209 self
._FinalBuildTargetList
.add(LastTarget
)
3212 Target
= RuleObject
.Apply(Source
, self
.BuildRuleOrder
)
3215 self
._FinalBuildTargetList
.add(LastTarget
)
3217 elif not Target
.Outputs
:
3218 # Only do build for target with outputs
3219 self
._FinalBuildTargetList
.add(Target
)
3221 if FileType
not in self
._BuildTargets
:
3222 self
._BuildTargets
[FileType
] = set()
3223 self
._BuildTargets
[FileType
].add(Target
)
3225 if not Source
.IsBinary
and Source
== File
:
3226 self
._IntroBuildTargetList
.add(Target
)
3228 # to avoid cyclic rule
3229 if FileType
in RuleChain
:
3232 RuleChain
.append(FileType
)
3233 SourceList
.extend(Target
.Outputs
)
3235 FileType
= TAB_UNKNOWN_FILE
3237 def _GetTargets(self
):
3238 if self
._BuildTargets
== None:
3239 self
._IntroBuildTargetList
= set()
3240 self
._FinalBuildTargetList
= set()
3241 self
._BuildTargets
= {}
3242 self
._FileTypes
= {}
3244 #TRICK: call _GetSourceFileList to apply build rule for source files
3245 if self
.SourceFileList
:
3248 #TRICK: call _GetBinaryFileList to apply build rule for binary files
3249 if self
.BinaryFileList
:
3252 return self
._BuildTargets
3254 def _GetIntroTargetList(self
):
3256 return self
._IntroBuildTargetList
3258 def _GetFinalTargetList(self
):
3260 return self
._FinalBuildTargetList
3262 def _GetFileTypes(self
):
3264 return self
._FileTypes
3266 ## Get the list of package object the module depends on
3268 # @retval list The package object list
3270 def _GetDependentPackageList(self
):
3271 return self
.Module
.Packages
3273 ## Return the list of auto-generated code file
3275 # @retval list The list of auto-generated file
3277 def _GetAutoGenFileList(self
):
3278 UniStringAutoGenC
= True
3279 UniStringBinBuffer
= StringIO()
3280 if self
.BuildType
== 'UEFI_HII':
3281 UniStringAutoGenC
= False
3282 if self
._AutoGenFileList
== None:
3283 self
._AutoGenFileList
= {}
3284 AutoGenC
= TemplateString()
3285 AutoGenH
= TemplateString()
3286 StringH
= TemplateString()
3287 GenC
.CreateCode(self
, AutoGenC
, AutoGenH
, StringH
, UniStringAutoGenC
, UniStringBinBuffer
)
3289 # AutoGen.c is generated if there are library classes in inf, or there are object files
3291 if str(AutoGenC
) != "" and (len(self
.Module
.LibraryClasses
) > 0
3292 or TAB_OBJECT_FILE
in self
.FileTypes
):
3293 AutoFile
= PathClass(gAutoGenCodeFileName
, self
.DebugDir
)
3294 self
._AutoGenFileList
[AutoFile
] = str(AutoGenC
)
3295 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3296 if str(AutoGenH
) != "":
3297 AutoFile
= PathClass(gAutoGenHeaderFileName
, self
.DebugDir
)
3298 self
._AutoGenFileList
[AutoFile
] = str(AutoGenH
)
3299 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3300 if str(StringH
) != "":
3301 AutoFile
= PathClass(gAutoGenStringFileName
% {"module_name":self
.Name
}, self
.DebugDir
)
3302 self
._AutoGenFileList
[AutoFile
] = str(StringH
)
3303 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3304 if UniStringBinBuffer
!= None and UniStringBinBuffer
.getvalue() != "":
3305 AutoFile
= PathClass(gAutoGenStringFormFileName
% {"module_name":self
.Name
}, self
.OutputDir
)
3306 self
._AutoGenFileList
[AutoFile
] = UniStringBinBuffer
.getvalue()
3307 AutoFile
.IsBinary
= True
3308 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3309 if UniStringBinBuffer
!= None:
3310 UniStringBinBuffer
.close()
3311 return self
._AutoGenFileList
3313 ## Return the list of library modules explicitly or implicityly used by this module
3314 def _GetLibraryList(self
):
3315 if self
._DependentLibraryList
== None:
3316 # only merge library classes and PCD for non-library module
3318 self
._DependentLibraryList
= []
3320 if self
.AutoGenVersion
< 0x00010005:
3321 self
._DependentLibraryList
= self
.PlatformInfo
.ResolveLibraryReference(self
.Module
)
3323 self
._DependentLibraryList
= self
.PlatformInfo
.ApplyLibraryInstance(self
.Module
)
3324 return self
._DependentLibraryList
3327 def UpdateComments(Recver
, Src
):
3329 if Key
not in Recver
:
3331 Recver
[Key
].extend(Src
[Key
])
3332 ## Get the list of PCDs from current module
3334 # @retval list The list of PCD
3336 def _GetModulePcdList(self
):
3337 if self
._ModulePcdList
== None:
3338 # apply PCD settings from platform
3339 self
._ModulePcdList
= self
.PlatformInfo
.ApplyPcdSetting(self
.Module
, self
.Module
.Pcds
)
3340 self
.UpdateComments(self
._PcdComments
, self
.Module
.PcdComments
)
3341 return self
._ModulePcdList
3343 ## Get the list of PCDs from dependent libraries
3345 # @retval list The list of PCD
3347 def _GetLibraryPcdList(self
):
3348 if self
._LibraryPcdList
== None:
3350 if not self
.IsLibrary
:
3351 # get PCDs from dependent libraries
3352 for Library
in self
.DependentLibraryList
:
3353 self
.UpdateComments(self
._PcdComments
, Library
.PcdComments
)
3354 for Key
in Library
.Pcds
:
3355 # skip duplicated PCDs
3356 if Key
in self
.Module
.Pcds
or Key
in Pcds
:
3358 Pcds
[Key
] = copy
.copy(Library
.Pcds
[Key
])
3359 # apply PCD settings from platform
3360 self
._LibraryPcdList
= self
.PlatformInfo
.ApplyPcdSetting(self
.Module
, Pcds
)
3362 self
._LibraryPcdList
= []
3363 return self
._LibraryPcdList
3365 ## Get the GUID value mapping
3367 # @retval dict The mapping between GUID cname and its value
3369 def _GetGuidList(self
):
3370 if self
._GuidList
== None:
3371 self
._GuidList
= sdict()
3372 self
._GuidList
.update(self
.Module
.Guids
)
3373 for Library
in self
.DependentLibraryList
:
3374 self
._GuidList
.update(Library
.Guids
)
3375 self
.UpdateComments(self
._GuidComments
, Library
.GuidComments
)
3376 self
.UpdateComments(self
._GuidComments
, self
.Module
.GuidComments
)
3377 return self
._GuidList
3379 def GetGuidsUsedByPcd(self
):
3380 if self
._GuidsUsedByPcd
== None:
3381 self
._GuidsUsedByPcd
= sdict()
3382 self
._GuidsUsedByPcd
.update(self
.Module
.GetGuidsUsedByPcd())
3383 for Library
in self
.DependentLibraryList
:
3384 self
._GuidsUsedByPcd
.update(Library
.GetGuidsUsedByPcd())
3385 return self
._GuidsUsedByPcd
3386 ## Get the protocol value mapping
3388 # @retval dict The mapping between protocol cname and its value
3390 def _GetProtocolList(self
):
3391 if self
._ProtocolList
== None:
3392 self
._ProtocolList
= sdict()
3393 self
._ProtocolList
.update(self
.Module
.Protocols
)
3394 for Library
in self
.DependentLibraryList
:
3395 self
._ProtocolList
.update(Library
.Protocols
)
3396 self
.UpdateComments(self
._ProtocolComments
, Library
.ProtocolComments
)
3397 self
.UpdateComments(self
._ProtocolComments
, self
.Module
.ProtocolComments
)
3398 return self
._ProtocolList
3400 ## Get the PPI value mapping
3402 # @retval dict The mapping between PPI cname and its value
3404 def _GetPpiList(self
):
3405 if self
._PpiList
== None:
3406 self
._PpiList
= sdict()
3407 self
._PpiList
.update(self
.Module
.Ppis
)
3408 for Library
in self
.DependentLibraryList
:
3409 self
._PpiList
.update(Library
.Ppis
)
3410 self
.UpdateComments(self
._PpiComments
, Library
.PpiComments
)
3411 self
.UpdateComments(self
._PpiComments
, self
.Module
.PpiComments
)
3412 return self
._PpiList
3414 ## Get the list of include search path
3416 # @retval list The list path
3418 def _GetIncludePathList(self
):
3419 if self
._IncludePathList
== None:
3420 self
._IncludePathList
= []
3421 if self
.AutoGenVersion
< 0x00010005:
3422 for Inc
in self
.Module
.Includes
:
3423 if Inc
not in self
._IncludePathList
:
3424 self
._IncludePathList
.append(Inc
)
3426 Inc
= path
.join(Inc
, self
.Arch
.capitalize())
3427 if os
.path
.exists(Inc
) and Inc
not in self
._IncludePathList
:
3428 self
._IncludePathList
.append(Inc
)
3429 # Edk module needs to put DEBUG_DIR at the end of search path and not to use SOURCE_DIR all the time
3430 self
._IncludePathList
.append(self
.DebugDir
)
3432 self
._IncludePathList
.append(self
.MetaFile
.Dir
)
3433 self
._IncludePathList
.append(self
.DebugDir
)
3435 for Package
in self
.Module
.Packages
:
3436 PackageDir
= mws
.join(self
.WorkspaceDir
, Package
.MetaFile
.Dir
)
3437 if PackageDir
not in self
._IncludePathList
:
3438 self
._IncludePathList
.append(PackageDir
)
3439 IncludesList
= Package
.Includes
3440 if Package
._PrivateIncludes
:
3441 if not self
.MetaFile
.Path
.startswith(PackageDir
):
3442 IncludesList
= list(set(Package
.Includes
).difference(set(Package
._PrivateIncludes
)))
3443 for Inc
in IncludesList
:
3444 if Inc
not in self
._IncludePathList
:
3445 self
._IncludePathList
.append(str(Inc
))
3446 return self
._IncludePathList
3448 def _GetIncludePathLength(self
):
3449 self
._IncludePathLength
= 0
3450 if self
._IncludePathList
:
3451 for inc
in self
._IncludePathList
:
3452 self
._IncludePathLength
+= len(' ' + inc
)
3453 return self
._IncludePathLength
3455 ## Get HII EX PCDs which maybe used by VFR
3457 # efivarstore used by VFR may relate with HII EX PCDs
3458 # Get the variable name and GUID from efivarstore and HII EX PCD
3459 # List the HII EX PCDs in As Built INF if both name and GUID match.
3461 # @retval list HII EX PCDs
3463 def _GetPcdsMaybeUsedByVfr(self
):
3464 if not self
.SourceFileList
:
3468 for SrcFile
in self
.SourceFileList
:
3469 if SrcFile
.Ext
.lower() != '.vfr':
3471 Vfri
= os
.path
.join(self
.OutputDir
, SrcFile
.BaseName
+ '.i')
3472 if not os
.path
.exists(Vfri
):
3474 VfriFile
= open(Vfri
, 'r')
3475 Content
= VfriFile
.read()
3477 Pos
= Content
.find('efivarstore')
3480 # Make sure 'efivarstore' is the start of efivarstore statement
3481 # In case of the value of 'name' (name = efivarstore) is equal to 'efivarstore'
3484 while Index
>= 0 and Content
[Index
] in ' \t\r\n':
3486 if Index
>= 0 and Content
[Index
] != ';':
3487 Pos
= Content
.find('efivarstore', Pos
+ len('efivarstore'))
3490 # 'efivarstore' must be followed by name and guid
3492 Name
= gEfiVarStoreNamePattern
.search(Content
, Pos
)
3495 Guid
= gEfiVarStoreGuidPattern
.search(Content
, Pos
)
3498 NameArray
= ConvertStringToByteArray('L"' + Name
.group(1) + '"')
3499 NameGuids
.append((NameArray
, GuidStructureStringToGuidString(Guid
.group(1))))
3500 Pos
= Content
.find('efivarstore', Name
.end())
3504 for Pcd
in self
.PlatformInfo
.Platform
.Pcds
.values():
3505 if Pcd
.Type
!= TAB_PCDS_DYNAMIC_EX_HII
:
3507 for SkuName
in Pcd
.SkuInfoList
:
3508 SkuInfo
= Pcd
.SkuInfoList
[SkuName
]
3509 Name
= ConvertStringToByteArray(SkuInfo
.VariableName
)
3510 Value
= GuidValue(SkuInfo
.VariableGuid
, self
.PlatformInfo
.PackageList
, self
.MetaFile
.Path
)
3513 Guid
= GuidStructureStringToGuidString(Value
)
3514 if (Name
, Guid
) in NameGuids
and Pcd
not in HiiExPcds
:
3515 HiiExPcds
.append(Pcd
)
3520 def _GenOffsetBin(self
):
3522 for SourceFile
in self
.Module
.Sources
:
3523 if SourceFile
.Type
.upper() == ".VFR" :
3525 # search the .map file to find the offset of vfr binary in the PE32+/TE file.
3527 VfrUniBaseName
[SourceFile
.BaseName
] = (SourceFile
.BaseName
+ "Bin")
3528 if SourceFile
.Type
.upper() == ".UNI" :
3530 # search the .map file to find the offset of Uni strings binary in the PE32+/TE file.
3532 VfrUniBaseName
["UniOffsetName"] = (self
.Name
+ "Strings")
3534 if len(VfrUniBaseName
) == 0:
3536 MapFileName
= os
.path
.join(self
.OutputDir
, self
.Name
+ ".map")
3537 EfiFileName
= os
.path
.join(self
.OutputDir
, self
.Name
+ ".efi")
3538 VfrUniOffsetList
= GetVariableOffset(MapFileName
, EfiFileName
, VfrUniBaseName
.values())
3539 if not VfrUniOffsetList
:
3542 OutputName
= '%sOffset.bin' % self
.Name
3543 UniVfrOffsetFileName
= os
.path
.join( self
.OutputDir
, OutputName
)
3546 fInputfile
= open(UniVfrOffsetFileName
, "wb+", 0)
3548 EdkLogger
.error("build", FILE_OPEN_FAILURE
, "File open failed for %s" % UniVfrOffsetFileName
,None)
3550 # Use a instance of StringIO to cache data
3551 fStringIO
= StringIO('')
3553 for Item
in VfrUniOffsetList
:
3554 if (Item
[0].find("Strings") != -1):
3556 # UNI offset in image.
3558 # { 0x8913c5e0, 0x33f6, 0x4d86, { 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66 } }
3560 UniGuid
= [0xe0, 0xc5, 0x13, 0x89, 0xf6, 0x33, 0x86, 0x4d, 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66]
3561 UniGuid
= [chr(ItemGuid
) for ItemGuid
in UniGuid
]
3562 fStringIO
.write(''.join(UniGuid
))
3563 UniValue
= pack ('Q', int (Item
[1], 16))
3564 fStringIO
.write (UniValue
)
3567 # VFR binary offset in image.
3569 # { 0xd0bc7cb4, 0x6a47, 0x495f, { 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2 } };
3571 VfrGuid
= [0xb4, 0x7c, 0xbc, 0xd0, 0x47, 0x6a, 0x5f, 0x49, 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2]
3572 VfrGuid
= [chr(ItemGuid
) for ItemGuid
in VfrGuid
]
3573 fStringIO
.write(''.join(VfrGuid
))
3575 VfrValue
= pack ('Q', int (Item
[1], 16))
3576 fStringIO
.write (VfrValue
)
3578 # write data into file.
3581 fInputfile
.write (fStringIO
.getvalue())
3583 EdkLogger
.error("build", FILE_WRITE_FAILURE
, "Write data to file %s failed, please check whether the "
3584 "file been locked or using by other applications." %UniVfrOffsetFileName
,None)
3590 ## Create AsBuilt INF file the module
3592 def CreateAsBuiltInf(self
):
3593 if self
.IsAsBuiltInfCreated
:
3596 # Skip the following code for EDK I inf
3597 if self
.AutoGenVersion
< 0x00010005:
3600 # Skip the following code for libraries
3604 # Skip the following code for modules with no source files
3605 if self
.SourceFileList
== None or self
.SourceFileList
== []:
3608 # Skip the following code for modules without any binary files
3609 if self
.BinaryFileList
<> None and self
.BinaryFileList
<> []:
3612 ### TODO: How to handles mixed source and binary modules
3614 # Find all DynamicEx and PatchableInModule PCDs used by this module and dependent libraries
3615 # Also find all packages that the DynamicEx PCDs depend on
3620 PcdTokenSpaceList
= []
3621 for Pcd
in self
.ModulePcdList
+ self
.LibraryPcdList
:
3622 if Pcd
.Type
== TAB_PCDS_PATCHABLE_IN_MODULE
:
3623 PatchablePcds
+= [Pcd
]
3624 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, 'PatchableInModule'))
3625 elif Pcd
.Type
in GenC
.gDynamicExPcd
:
3628 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, 'DynamicEx'))
3629 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, 'Dynamic'))
3630 PcdTokenSpaceList
.append(Pcd
.TokenSpaceGuidCName
)
3632 GuidList
.update(self
.GuidList
)
3633 for TokenSpace
in self
.GetGuidsUsedByPcd():
3634 # If token space is not referred by patch PCD or Ex PCD, remove the GUID from GUID list
3635 # The GUIDs in GUIDs section should really be the GUIDs in source INF or referred by Ex an patch PCDs
3636 if TokenSpace
not in PcdTokenSpaceList
and TokenSpace
in GuidList
:
3637 GuidList
.pop(TokenSpace
)
3638 CheckList
= (GuidList
, self
.PpiList
, self
.ProtocolList
, PcdCheckList
)
3639 for Package
in self
.DerivedPackageList
:
3640 if Package
in Packages
:
3642 BeChecked
= (Package
.Guids
, Package
.Ppis
, Package
.Protocols
, Package
.Pcds
)
3644 for Index
in range(len(BeChecked
)):
3645 for Item
in CheckList
[Index
]:
3646 if Item
in BeChecked
[Index
]:
3647 Packages
+= [Package
]
3652 VfrPcds
= self
._GetPcdsMaybeUsedByVfr
()
3653 for Pkg
in self
.PlatformInfo
.PackageList
:
3656 for VfrPcd
in VfrPcds
:
3657 if ((VfrPcd
.TokenCName
, VfrPcd
.TokenSpaceGuidCName
, 'DynamicEx') in Pkg
.Pcds
or
3658 (VfrPcd
.TokenCName
, VfrPcd
.TokenSpaceGuidCName
, 'Dynamic') in Pkg
.Pcds
):
3662 ModuleType
= self
.ModuleType
3663 if ModuleType
== 'UEFI_DRIVER' and self
.DepexGenerated
:
3664 ModuleType
= 'DXE_DRIVER'
3667 if self
.PcdIsDriver
!= '':
3668 DriverType
= self
.PcdIsDriver
3671 MDefs
= self
.Module
.Defines
3674 'module_name' : self
.Name
,
3675 'module_guid' : Guid
,
3676 'module_module_type' : ModuleType
,
3677 'module_version_string' : [MDefs
['VERSION_STRING']] if 'VERSION_STRING' in MDefs
else [],
3678 'pcd_is_driver_string' : [],
3679 'module_uefi_specification_version' : [],
3680 'module_pi_specification_version' : [],
3681 'module_entry_point' : self
.Module
.ModuleEntryPointList
,
3682 'module_unload_image' : self
.Module
.ModuleUnloadImageList
,
3683 'module_constructor' : self
.Module
.ConstructorList
,
3684 'module_destructor' : self
.Module
.DestructorList
,
3685 'module_shadow' : [MDefs
['SHADOW']] if 'SHADOW' in MDefs
else [],
3686 'module_pci_vendor_id' : [MDefs
['PCI_VENDOR_ID']] if 'PCI_VENDOR_ID' in MDefs
else [],
3687 'module_pci_device_id' : [MDefs
['PCI_DEVICE_ID']] if 'PCI_DEVICE_ID' in MDefs
else [],
3688 'module_pci_class_code' : [MDefs
['PCI_CLASS_CODE']] if 'PCI_CLASS_CODE' in MDefs
else [],
3689 'module_pci_revision' : [MDefs
['PCI_REVISION']] if 'PCI_REVISION' in MDefs
else [],
3690 'module_build_number' : [MDefs
['BUILD_NUMBER']] if 'BUILD_NUMBER' in MDefs
else [],
3691 'module_spec' : [MDefs
['SPEC']] if 'SPEC' in MDefs
else [],
3692 'module_uefi_hii_resource_section' : [MDefs
['UEFI_HII_RESOURCE_SECTION']] if 'UEFI_HII_RESOURCE_SECTION' in MDefs
else [],
3693 'module_uni_file' : [MDefs
['MODULE_UNI_FILE']] if 'MODULE_UNI_FILE' in MDefs
else [],
3694 'module_arch' : self
.Arch
,
3695 'package_item' : ['%s' % (Package
.MetaFile
.File
.replace('\\', '/')) for Package
in Packages
],
3697 'patchablepcd_item' : [],
3699 'protocol_item' : [],
3703 'libraryclasses_item' : []
3706 if self
.AutoGenVersion
> int(gInfSpecVersion
, 0):
3707 AsBuiltInfDict
['module_inf_version'] = '0x%08x' % self
.AutoGenVersion
3709 AsBuiltInfDict
['module_inf_version'] = gInfSpecVersion
3712 AsBuiltInfDict
['pcd_is_driver_string'] += [DriverType
]
3714 if 'UEFI_SPECIFICATION_VERSION' in self
.Specification
:
3715 AsBuiltInfDict
['module_uefi_specification_version'] += [self
.Specification
['UEFI_SPECIFICATION_VERSION']]
3716 if 'PI_SPECIFICATION_VERSION' in self
.Specification
:
3717 AsBuiltInfDict
['module_pi_specification_version'] += [self
.Specification
['PI_SPECIFICATION_VERSION']]
3719 OutputDir
= self
.OutputDir
.replace('\\', '/').strip('/')
3721 for Item
in self
.CodaTargetList
:
3722 File
= Item
.Target
.Path
.replace('\\', '/').strip('/').replace(OutputDir
, '').strip('/')
3723 if Item
.Target
.Ext
.lower() == '.aml':
3724 AsBuiltInfDict
['binary_item'] += ['ASL|' + File
]
3725 elif Item
.Target
.Ext
.lower() == '.acpi':
3726 AsBuiltInfDict
['binary_item'] += ['ACPI|' + File
]
3727 elif Item
.Target
.Ext
.lower() == '.efi':
3728 AsBuiltInfDict
['binary_item'] += ['PE32|' + self
.Name
+ '.efi']
3730 AsBuiltInfDict
['binary_item'] += ['BIN|' + File
]
3731 if self
.DepexGenerated
:
3732 if self
.ModuleType
in ['PEIM']:
3733 AsBuiltInfDict
['binary_item'] += ['PEI_DEPEX|' + self
.Name
+ '.depex']
3734 if self
.ModuleType
in ['DXE_DRIVER', 'DXE_RUNTIME_DRIVER', 'DXE_SAL_DRIVER', 'UEFI_DRIVER']:
3735 AsBuiltInfDict
['binary_item'] += ['DXE_DEPEX|' + self
.Name
+ '.depex']
3736 if self
.ModuleType
in ['DXE_SMM_DRIVER']:
3737 AsBuiltInfDict
['binary_item'] += ['SMM_DEPEX|' + self
.Name
+ '.depex']
3739 Bin
= self
._GenOffsetBin
()
3741 AsBuiltInfDict
['binary_item'] += ['BIN|%s' % Bin
]
3743 for Root
, Dirs
, Files
in os
.walk(OutputDir
):
3745 if File
.lower().endswith('.pdb'):
3746 AsBuiltInfDict
['binary_item'] += ['DISPOSABLE|' + File
]
3747 HeaderComments
= self
.Module
.HeaderComments
3749 for Index
in range(len(HeaderComments
)):
3750 if HeaderComments
[Index
].find('@BinaryHeader') != -1:
3751 HeaderComments
[Index
] = HeaderComments
[Index
].replace('@BinaryHeader', '@file')
3754 AsBuiltInfDict
['header_comments'] = '\n'.join(HeaderComments
[StartPos
:]).replace(':#', '://')
3755 AsBuiltInfDict
['tail_comments'] = '\n'.join(self
.Module
.TailComments
)
3758 (self
.ProtocolList
, self
._ProtocolComments
, 'protocol_item'),
3759 (self
.PpiList
, self
._PpiComments
, 'ppi_item'),
3760 (GuidList
, self
._GuidComments
, 'guid_item')
3762 for Item
in GenList
:
3763 for CName
in Item
[0]:
3765 if CName
in Item
[1]:
3766 Comments
= '\n '.join(Item
[1][CName
])
3769 Entry
= Comments
+ '\n ' + CName
3770 AsBuiltInfDict
[Item
[2]].append(Entry
)
3771 PatchList
= parsePcdInfoFromMapFile(
3772 os
.path
.join(self
.OutputDir
, self
.Name
+ '.map'),
3773 os
.path
.join(self
.OutputDir
, self
.Name
+ '.efi')
3776 for Pcd
in PatchablePcds
:
3777 TokenCName
= Pcd
.TokenCName
3778 for PcdItem
in GlobalData
.MixedPcd
:
3779 if (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
3780 TokenCName
= PcdItem
[0]
3782 for PatchPcd
in PatchList
:
3783 if TokenCName
== PatchPcd
[0]:
3788 if Pcd
.DatumType
!= 'VOID*':
3789 HexFormat
= '0x%02x'
3790 if Pcd
.DatumType
== 'UINT16':
3791 HexFormat
= '0x%04x'
3792 elif Pcd
.DatumType
== 'UINT32':
3793 HexFormat
= '0x%08x'
3794 elif Pcd
.DatumType
== 'UINT64':
3795 HexFormat
= '0x%016x'
3796 PcdValue
= HexFormat
% int(Pcd
.DefaultValue
, 0)
3798 if Pcd
.MaxDatumSize
== None or Pcd
.MaxDatumSize
== '':
3799 EdkLogger
.error("build", AUTOGEN_ERROR
,
3800 "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
3802 ArraySize
= int(Pcd
.MaxDatumSize
, 0)
3803 PcdValue
= Pcd
.DefaultValue
3804 if PcdValue
[0] != '{':
3806 if PcdValue
[0] == 'L':
3808 PcdValue
= PcdValue
.lstrip('L')
3809 PcdValue
= eval(PcdValue
)
3811 for Index
in range(0, len(PcdValue
)):
3813 CharVal
= ord(PcdValue
[Index
])
3814 NewValue
= NewValue
+ '0x%02x' % (CharVal
& 0x00FF) + ', ' \
3815 + '0x%02x' % (CharVal
>> 8) + ', '
3817 NewValue
= NewValue
+ '0x%02x' % (ord(PcdValue
[Index
]) % 0x100) + ', '
3820 Padding
= Padding
* 2
3821 ArraySize
= ArraySize
/ 2
3822 if ArraySize
< (len(PcdValue
) + 1):
3823 EdkLogger
.error("build", AUTOGEN_ERROR
,
3824 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
3826 if ArraySize
> len(PcdValue
) + 1:
3827 NewValue
= NewValue
+ Padding
* (ArraySize
- len(PcdValue
) - 1)
3828 PcdValue
= NewValue
+ Padding
.strip().rstrip(',') + '}'
3829 elif len(PcdValue
.split(',')) <= ArraySize
:
3830 PcdValue
= PcdValue
.rstrip('}') + ', 0x00' * (ArraySize
- len(PcdValue
.split(',')))
3833 EdkLogger
.error("build", AUTOGEN_ERROR
,
3834 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
3836 PcdItem
= '%s.%s|%s|0x%X' % \
3837 (Pcd
.TokenSpaceGuidCName
, TokenCName
, PcdValue
, PatchPcd
[1])
3839 if (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) in self
._PcdComments
:
3840 PcdComments
= '\n '.join(self
._PcdComments
[Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
])
3842 PcdItem
= PcdComments
+ '\n ' + PcdItem
3843 AsBuiltInfDict
['patchablepcd_item'].append(PcdItem
)
3846 for Pcd
in Pcds
+ VfrPcds
:
3851 TokenCName
= Pcd
.TokenCName
3852 for PcdItem
in GlobalData
.MixedPcd
:
3853 if (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
3854 TokenCName
= PcdItem
[0]
3856 if Pcd
.Type
== TAB_PCDS_DYNAMIC_EX_HII
:
3857 for SkuName
in Pcd
.SkuInfoList
:
3858 SkuInfo
= Pcd
.SkuInfoList
[SkuName
]
3859 SkuId
= SkuInfo
.SkuId
3860 HiiInfo
= '## %s|%s|%s' % (SkuInfo
.VariableName
, SkuInfo
.VariableGuid
, SkuInfo
.VariableOffset
)
3864 # Don't generate duplicated HII PCD
3866 if (SkuId
, Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) in HiiPcds
:
3869 HiiPcds
.append((SkuId
, Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
))
3870 if (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) in self
._PcdComments
:
3871 PcdCommentList
= self
._PcdComments
[Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
][:]
3875 for Index
, Comment
in enumerate(PcdCommentList
):
3876 for Usage
in UsageList
:
3877 if Comment
.find(Usage
) != -1:
3881 if UsageIndex
!= -1:
3882 PcdCommentList
[UsageIndex
] = '## %s %s %s' % (UsageStr
, HiiInfo
, PcdCommentList
[UsageIndex
].replace(UsageStr
, ''))
3884 PcdCommentList
.append('## UNDEFINED ' + HiiInfo
)
3885 PcdComments
= '\n '.join(PcdCommentList
)
3886 PcdEntry
= Pcd
.TokenSpaceGuidCName
+ '.' + TokenCName
3888 PcdEntry
= PcdComments
+ '\n ' + PcdEntry
3889 AsBuiltInfDict
['pcd_item'] += [PcdEntry
]
3890 for Item
in self
.BuildOption
:
3891 if 'FLAGS' in self
.BuildOption
[Item
]:
3892 AsBuiltInfDict
['flags_item'] += ['%s:%s_%s_%s_%s_FLAGS = %s' % (self
.ToolChainFamily
, self
.BuildTarget
, self
.ToolChain
, self
.Arch
, Item
, self
.BuildOption
[Item
]['FLAGS'].strip())]
3894 # Generated LibraryClasses section in comments.
3895 for Library
in self
.LibraryAutoGenList
:
3896 AsBuiltInfDict
['libraryclasses_item'] += [Library
.MetaFile
.File
.replace('\\', '/')]
3898 # Generated depex expression section in comments.
3899 AsBuiltInfDict
['depexsection_item'] = ''
3900 DepexExpresion
= self
._GetDepexExpresionString
()
3902 AsBuiltInfDict
['depexsection_item'] = DepexExpresion
3904 AsBuiltInf
= TemplateString()
3905 AsBuiltInf
.Append(gAsBuiltInfHeaderString
.Replace(AsBuiltInfDict
))
3907 SaveFileOnChange(os
.path
.join(self
.OutputDir
, self
.Name
+ '.inf'), str(AsBuiltInf
), False)
3909 self
.IsAsBuiltInfCreated
= True
3911 ## Create makefile for the module and its dependent libraries
3913 # @param CreateLibraryMakeFile Flag indicating if or not the makefiles of
3914 # dependent libraries will be created
3916 def CreateMakeFile(self
, CreateLibraryMakeFile
=True):
3917 # Ignore generating makefile when it is a binary module
3918 if self
.IsBinaryModule
:
3921 if self
.IsMakeFileCreated
:
3924 if not self
.IsLibrary
and CreateLibraryMakeFile
:
3925 for LibraryAutoGen
in self
.LibraryAutoGenList
:
3926 LibraryAutoGen
.CreateMakeFile()
3928 if len(self
.CustomMakefile
) == 0:
3929 Makefile
= GenMake
.ModuleMakefile(self
)
3931 Makefile
= GenMake
.CustomMakefile(self
)
3932 if Makefile
.Generate():
3933 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated makefile for module %s [%s]" %
3934 (self
.Name
, self
.Arch
))
3936 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Skipped the generation of makefile for module %s [%s]" %
3937 (self
.Name
, self
.Arch
))
3939 self
.IsMakeFileCreated
= True
3941 def CopyBinaryFiles(self
):
3942 for File
in self
.Module
.Binaries
:
3944 DstPath
= os
.path
.join(self
.OutputDir
, os
.path
.basename(SrcPath
))
3945 CopyLongFilePath(SrcPath
, DstPath
)
3946 ## Create autogen code for the module and its dependent libraries
3948 # @param CreateLibraryCodeFile Flag indicating if or not the code of
3949 # dependent libraries will be created
3951 def CreateCodeFile(self
, CreateLibraryCodeFile
=True):
3952 if self
.IsCodeFileCreated
:
3955 # Need to generate PcdDatabase even PcdDriver is binarymodule
3956 if self
.IsBinaryModule
and self
.PcdIsDriver
!= '':
3957 CreatePcdDatabaseCode(self
, TemplateString(), TemplateString())
3959 if self
.IsBinaryModule
:
3961 self
.CopyBinaryFiles()
3964 if not self
.IsLibrary
and CreateLibraryCodeFile
:
3965 for LibraryAutoGen
in self
.LibraryAutoGenList
:
3966 LibraryAutoGen
.CreateCodeFile()
3969 IgoredAutoGenList
= []
3971 for File
in self
.AutoGenFileList
:
3972 if GenC
.Generate(File
.Path
, self
.AutoGenFileList
[File
], File
.IsBinary
):
3973 #Ignore Edk AutoGen.c
3974 if self
.AutoGenVersion
< 0x00010005 and File
.Name
== 'AutoGen.c':
3977 AutoGenList
.append(str(File
))
3979 IgoredAutoGenList
.append(str(File
))
3981 # Skip the following code for EDK I inf
3982 if self
.AutoGenVersion
< 0x00010005:
3985 for ModuleType
in self
.DepexList
:
3986 # Ignore empty [depex] section or [depex] section for "USER_DEFINED" module
3987 if len(self
.DepexList
[ModuleType
]) == 0 or ModuleType
== "USER_DEFINED":
3990 Dpx
= GenDepex
.DependencyExpression(self
.DepexList
[ModuleType
], ModuleType
, True)
3991 DpxFile
= gAutoGenDepexFileName
% {"module_name" : self
.Name
}
3993 if len(Dpx
.PostfixNotation
) <> 0:
3994 self
.DepexGenerated
= True
3996 if Dpx
.Generate(path
.join(self
.OutputDir
, DpxFile
)):
3997 AutoGenList
.append(str(DpxFile
))
3999 IgoredAutoGenList
.append(str(DpxFile
))
4001 if IgoredAutoGenList
== []:
4002 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated [%s] files for module %s [%s]" %
4003 (" ".join(AutoGenList
), self
.Name
, self
.Arch
))
4004 elif AutoGenList
== []:
4005 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Skipped the generation of [%s] files for module %s [%s]" %
4006 (" ".join(IgoredAutoGenList
), self
.Name
, self
.Arch
))
4008 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated [%s] (skipped %s) files for module %s [%s]" %
4009 (" ".join(AutoGenList
), " ".join(IgoredAutoGenList
), self
.Name
, self
.Arch
))
4011 self
.IsCodeFileCreated
= True
4014 ## Summarize the ModuleAutoGen objects of all libraries used by this module
4015 def _GetLibraryAutoGenList(self
):
4016 if self
._LibraryAutoGenList
== None:
4017 self
._LibraryAutoGenList
= []
4018 for Library
in self
.DependentLibraryList
:
4025 self
.PlatformInfo
.MetaFile
4027 if La
not in self
._LibraryAutoGenList
:
4028 self
._LibraryAutoGenList
.append(La
)
4029 for Lib
in La
.CodaTargetList
:
4030 self
._ApplyBuildRule
(Lib
.Target
, TAB_UNKNOWN_FILE
)
4031 return self
._LibraryAutoGenList
4033 Module
= property(_GetModule
)
4034 Name
= property(_GetBaseName
)
4035 Guid
= property(_GetGuid
)
4036 Version
= property(_GetVersion
)
4037 ModuleType
= property(_GetModuleType
)
4038 ComponentType
= property(_GetComponentType
)
4039 BuildType
= property(_GetBuildType
)
4040 PcdIsDriver
= property(_GetPcdIsDriver
)
4041 AutoGenVersion
= property(_GetAutoGenVersion
)
4042 Macros
= property(_GetMacros
)
4043 Specification
= property(_GetSpecification
)
4045 IsLibrary
= property(_IsLibrary
)
4046 IsBinaryModule
= property(_IsBinaryModule
)
4047 BuildDir
= property(_GetBuildDir
)
4048 OutputDir
= property(_GetOutputDir
)
4049 DebugDir
= property(_GetDebugDir
)
4050 MakeFileDir
= property(_GetMakeFileDir
)
4051 CustomMakefile
= property(_GetCustomMakefile
)
4053 IncludePathList
= property(_GetIncludePathList
)
4054 IncludePathLength
= property(_GetIncludePathLength
)
4055 AutoGenFileList
= property(_GetAutoGenFileList
)
4056 UnicodeFileList
= property(_GetUnicodeFileList
)
4057 SourceFileList
= property(_GetSourceFileList
)
4058 BinaryFileList
= property(_GetBinaryFiles
) # FileType : [File List]
4059 Targets
= property(_GetTargets
)
4060 IntroTargetList
= property(_GetIntroTargetList
)
4061 CodaTargetList
= property(_GetFinalTargetList
)
4062 FileTypes
= property(_GetFileTypes
)
4063 BuildRules
= property(_GetBuildRules
)
4065 DependentPackageList
= property(_GetDependentPackageList
)
4066 DependentLibraryList
= property(_GetLibraryList
)
4067 LibraryAutoGenList
= property(_GetLibraryAutoGenList
)
4068 DerivedPackageList
= property(_GetDerivedPackageList
)
4070 ModulePcdList
= property(_GetModulePcdList
)
4071 LibraryPcdList
= property(_GetLibraryPcdList
)
4072 GuidList
= property(_GetGuidList
)
4073 ProtocolList
= property(_GetProtocolList
)
4074 PpiList
= property(_GetPpiList
)
4075 DepexList
= property(_GetDepexTokenList
)
4076 DxsFile
= property(_GetDxsFile
)
4077 DepexExpressionList
= property(_GetDepexExpressionTokenList
)
4078 BuildOption
= property(_GetModuleBuildOption
)
4079 BuildOptionIncPathList
= property(_GetBuildOptionIncPathList
)
4080 BuildCommand
= property(_GetBuildCommand
)
4082 FixedAtBuildPcds
= property(_GetFixedAtBuildPcds
)
4084 # This acts like the main() function for the script, unless it is 'import'ed into another script.
4085 if __name__
== '__main__':