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 for key
in self
.FdfProfile
.InfDict
:
336 for Arch
in self
.ArchList
:
337 Platform_cache
[Arch
] = self
.BuildDatabase
[self
.MetaFile
, Arch
, Target
, Toolchain
]
338 for Inf
in self
.FdfProfile
.InfDict
[key
]:
339 ModuleFile
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, Arch
)
340 for Arch
in self
.ArchList
:
341 if ModuleFile
in Platform_cache
[Arch
].Modules
:
344 ModuleData
= self
.BuildDatabase
[ModuleFile
, Arch
, Target
, Toolchain
]
345 if not ModuleData
.IsBinaryModule
:
346 EdkLogger
.error('build', PARSER_ERROR
, "Module %s NOT found in DSC file; Is it really a binary module?" % ModuleFile
)
349 for Arch
in self
.ArchList
:
351 Platform
= self
.BuildDatabase
[self
.MetaFile
, Arch
, Target
, Toolchain
]
352 for Inf
in self
.FdfProfile
.InfDict
[key
]:
353 ModuleFile
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, Arch
)
354 if ModuleFile
in Platform
.Modules
:
356 ModuleData
= self
.BuildDatabase
[ModuleFile
, Arch
, Target
, Toolchain
]
357 if not ModuleData
.IsBinaryModule
:
358 EdkLogger
.error('build', PARSER_ERROR
, "Module %s NOT found in DSC file; Is it really a binary module?" % ModuleFile
)
363 self
.FdfProfile
= None
364 if self
.FdTargetList
:
365 EdkLogger
.info("No flash definition file found. FD [%s] will be ignored." % " ".join(self
.FdTargetList
))
366 self
.FdTargetList
= []
367 if self
.FvTargetList
:
368 EdkLogger
.info("No flash definition file found. FV [%s] will be ignored." % " ".join(self
.FvTargetList
))
369 self
.FvTargetList
= []
370 if self
.CapTargetList
:
371 EdkLogger
.info("No flash definition file found. Capsule [%s] will be ignored." % " ".join(self
.CapTargetList
))
372 self
.CapTargetList
= []
374 # apply SKU and inject PCDs from Flash Definition file
375 for Arch
in self
.ArchList
:
376 Platform
= self
.BuildDatabase
[self
.MetaFile
, Arch
, Target
, Toolchain
]
380 PGen
= PlatformAutoGen(self
, self
.MetaFile
, Target
, Toolchain
, Arch
)
381 if GlobalData
.BuildOptionPcd
:
382 for i
, pcd
in enumerate(GlobalData
.BuildOptionPcd
):
383 if type(pcd
) is tuple:
385 (pcdname
, pcdvalue
) = pcd
.split('=')
387 EdkLogger
.error('build', AUTOGEN_ERROR
, "No Value specified for the PCD %s." % (pcdname
))
389 (TokenSpaceGuidCName
, TokenCName
) = pcdname
.split('.')
393 TokenSpaceGuidCName
= ''
394 HasTokenSpace
= False
395 TokenSpaceGuidCNameList
= []
399 for package
in PGen
.PackageList
:
400 for key
in package
.Pcds
:
401 PcdItem
= package
.Pcds
[key
]
403 if (PcdItem
.TokenCName
, PcdItem
.TokenSpaceGuidCName
) == (TokenCName
, TokenSpaceGuidCName
):
404 PcdDatumType
= PcdItem
.DatumType
405 NewValue
= self
._BuildOptionPcdValueFormat
(TokenSpaceGuidCName
, TokenCName
, PcdDatumType
, pcdvalue
)
408 if PcdItem
.TokenCName
== TokenCName
:
409 if not PcdItem
.TokenSpaceGuidCName
in TokenSpaceGuidCNameList
:
410 if len (TokenSpaceGuidCNameList
) < 1:
411 TokenSpaceGuidCNameList
.append(PcdItem
.TokenSpaceGuidCName
)
412 PcdDatumType
= PcdItem
.DatumType
413 TokenSpaceGuidCName
= PcdItem
.TokenSpaceGuidCName
414 NewValue
= self
._BuildOptionPcdValueFormat
(TokenSpaceGuidCName
, TokenCName
, PcdDatumType
, pcdvalue
)
420 "The Pcd %s is found under multiple different TokenSpaceGuid: %s and %s." % (TokenCName
, PcdItem
.TokenSpaceGuidCName
, TokenSpaceGuidCNameList
[0])
423 GlobalData
.BuildOptionPcd
[i
] = (TokenSpaceGuidCName
, TokenCName
, NewValue
)
427 EdkLogger
.error('build', AUTOGEN_ERROR
, "The Pcd %s.%s is not found in the DEC file." % (TokenSpaceGuidCName
, TokenCName
))
429 EdkLogger
.error('build', AUTOGEN_ERROR
, "The Pcd %s is not found in the DEC file." % (TokenCName
))
431 for BuildData
in PGen
.BuildDatabase
._CACHE
_.values():
432 if BuildData
.Arch
!= Arch
:
434 if BuildData
.MetaFile
.Ext
== '.dec':
436 for key
in BuildData
.Pcds
:
437 PcdItem
= BuildData
.Pcds
[key
]
438 if (TokenSpaceGuidCName
, TokenCName
) == (PcdItem
.TokenSpaceGuidCName
, PcdItem
.TokenCName
):
439 PcdItem
.DefaultValue
= NewValue
441 if (TokenCName
, TokenSpaceGuidCName
) in PcdSet
:
442 PcdSet
[(TokenCName
, TokenSpaceGuidCName
)] = NewValue
444 SourcePcdDict
= {'DynamicEx':[], 'PatchableInModule':[],'Dynamic':[],'FixedAtBuild':[]}
445 BinaryPcdDict
= {'DynamicEx':[], 'PatchableInModule':[]}
446 SourcePcdDict_Keys
= SourcePcdDict
.keys()
447 BinaryPcdDict_Keys
= BinaryPcdDict
.keys()
449 # generate the SourcePcdDict and BinaryPcdDict
450 for BuildData
in PGen
.BuildDatabase
._CACHE
_.values():
451 if BuildData
.Arch
!= Arch
:
453 if BuildData
.MetaFile
.Ext
== '.inf':
454 for key
in BuildData
.Pcds
:
455 if BuildData
.Pcds
[key
].Pending
:
456 if key
in Platform
.Pcds
:
457 PcdInPlatform
= Platform
.Pcds
[key
]
458 if PcdInPlatform
.Type
not in [None, '']:
459 BuildData
.Pcds
[key
].Type
= PcdInPlatform
.Type
461 if BuildData
.MetaFile
in Platform
.Modules
:
462 PlatformModule
= Platform
.Modules
[str(BuildData
.MetaFile
)]
463 if key
in PlatformModule
.Pcds
:
464 PcdInPlatform
= PlatformModule
.Pcds
[key
]
465 if PcdInPlatform
.Type
not in [None, '']:
466 BuildData
.Pcds
[key
].Type
= PcdInPlatform
.Type
468 if 'DynamicEx' in BuildData
.Pcds
[key
].Type
:
469 if BuildData
.IsBinaryModule
:
470 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) not in BinaryPcdDict
['DynamicEx']:
471 BinaryPcdDict
['DynamicEx'].append((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
473 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) not in SourcePcdDict
['DynamicEx']:
474 SourcePcdDict
['DynamicEx'].append((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
476 elif 'PatchableInModule' in BuildData
.Pcds
[key
].Type
:
477 if BuildData
.MetaFile
.Ext
== '.inf':
478 if BuildData
.IsBinaryModule
:
479 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) not in BinaryPcdDict
['PatchableInModule']:
480 BinaryPcdDict
['PatchableInModule'].append((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
482 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) not in SourcePcdDict
['PatchableInModule']:
483 SourcePcdDict
['PatchableInModule'].append((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
485 elif 'Dynamic' in BuildData
.Pcds
[key
].Type
:
486 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) not in SourcePcdDict
['Dynamic']:
487 SourcePcdDict
['Dynamic'].append((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
488 elif 'FixedAtBuild' in BuildData
.Pcds
[key
].Type
:
489 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) not in SourcePcdDict
['FixedAtBuild']:
490 SourcePcdDict
['FixedAtBuild'].append((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
495 # intersection the BinaryPCD for Mixed PCD
497 for i
in BinaryPcdDict_Keys
:
498 for j
in BinaryPcdDict_Keys
:
500 IntersectionList
= list(set(BinaryPcdDict
[i
]).intersection(set(BinaryPcdDict
[j
])))
501 for item
in IntersectionList
:
502 NewPcd1
= (item
[0] + '_' + i
, item
[1])
503 NewPcd2
= (item
[0] + '_' + j
, item
[1])
504 if item
not in GlobalData
.MixedPcd
:
505 GlobalData
.MixedPcd
[item
] = [NewPcd1
, NewPcd2
]
507 if NewPcd1
not in GlobalData
.MixedPcd
[item
]:
508 GlobalData
.MixedPcd
[item
].append(NewPcd1
)
509 if NewPcd2
not in GlobalData
.MixedPcd
[item
]:
510 GlobalData
.MixedPcd
[item
].append(NewPcd2
)
515 # intersection the SourcePCD and BinaryPCD for Mixed PCD
517 for i
in SourcePcdDict_Keys
:
518 for j
in BinaryPcdDict_Keys
:
520 IntersectionList
= list(set(SourcePcdDict
[i
]).intersection(set(BinaryPcdDict
[j
])))
521 for item
in IntersectionList
:
522 NewPcd1
= (item
[0] + '_' + i
, item
[1])
523 NewPcd2
= (item
[0] + '_' + j
, item
[1])
524 if item
not in GlobalData
.MixedPcd
:
525 GlobalData
.MixedPcd
[item
] = [NewPcd1
, NewPcd2
]
527 if NewPcd1
not in GlobalData
.MixedPcd
[item
]:
528 GlobalData
.MixedPcd
[item
].append(NewPcd1
)
529 if NewPcd2
not in GlobalData
.MixedPcd
[item
]:
530 GlobalData
.MixedPcd
[item
].append(NewPcd2
)
534 for BuildData
in PGen
.BuildDatabase
._CACHE
_.values():
535 if BuildData
.Arch
!= Arch
:
537 for key
in BuildData
.Pcds
:
538 for SinglePcd
in GlobalData
.MixedPcd
:
539 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) == SinglePcd
:
540 for item
in GlobalData
.MixedPcd
[SinglePcd
]:
541 Pcd_Type
= item
[0].split('_')[-1]
542 if (Pcd_Type
== BuildData
.Pcds
[key
].Type
) or (Pcd_Type
== TAB_PCDS_DYNAMIC_EX
and BuildData
.Pcds
[key
].Type
in GenC
.gDynamicExPcd
) or \
543 (Pcd_Type
== TAB_PCDS_DYNAMIC
and BuildData
.Pcds
[key
].Type
in GenC
.gDynamicPcd
):
544 Value
= BuildData
.Pcds
[key
]
545 Value
.TokenCName
= BuildData
.Pcds
[key
].TokenCName
+ '_' + Pcd_Type
547 newkey
= (Value
.TokenCName
, key
[1])
549 newkey
= (Value
.TokenCName
, key
[1], key
[2])
550 del BuildData
.Pcds
[key
]
551 BuildData
.Pcds
[newkey
] = Value
559 # handle the mixed pcd in FDF file
561 if key
in GlobalData
.MixedPcd
:
564 for item
in GlobalData
.MixedPcd
[key
]:
567 #Collect package set information from INF of FDF
569 for Inf
in ModuleList
:
570 ModuleFile
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, Arch
)
571 if ModuleFile
in Platform
.Modules
:
573 ModuleData
= self
.BuildDatabase
[ModuleFile
, Arch
, Target
, Toolchain
]
574 PkgSet
.update(ModuleData
.Packages
)
575 Pkgs
= list(PkgSet
) + list(PGen
.PackageList
)
578 DecPcds
[Pcd
[0], Pcd
[1]] = Pkg
.Pcds
[Pcd
]
579 DecPcdsKey
.add((Pcd
[0], Pcd
[1], Pcd
[2]))
581 Platform
.SkuName
= self
.SkuId
582 for Name
, Guid
in PcdSet
:
583 if (Name
, Guid
) not in DecPcds
:
587 "PCD (%s.%s) used in FDF is not declared in DEC files." % (Guid
, Name
),
588 File
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
][0],
589 Line
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
][1]
592 # Check whether Dynamic or DynamicEx PCD used in FDF file. If used, build break and give a error message.
593 if (Name
, Guid
, TAB_PCDS_FIXED_AT_BUILD
) in DecPcdsKey \
594 or (Name
, Guid
, TAB_PCDS_PATCHABLE_IN_MODULE
) in DecPcdsKey \
595 or (Name
, Guid
, TAB_PCDS_FEATURE_FLAG
) in DecPcdsKey
:
596 Platform
.AddPcd(Name
, Guid
, PcdSet
[Name
, Guid
])
598 elif (Name
, Guid
, TAB_PCDS_DYNAMIC
) in DecPcdsKey
or (Name
, Guid
, TAB_PCDS_DYNAMIC_EX
) in DecPcdsKey
:
602 "Using Dynamic or DynamicEx type of PCD [%s.%s] in FDF file is not allowed." % (Guid
, Name
),
603 File
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
][0],
604 Line
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
][1]
607 Pa
= PlatformAutoGen(self
, self
.MetaFile
, Target
, Toolchain
, Arch
)
609 # Explicitly collect platform's dynamic PCDs
611 Pa
.CollectPlatformDynamicPcds()
612 Pa
.CollectFixedAtBuildPcds()
613 self
.AutoGenObjectList
.append(Pa
)
616 # Check PCDs token value conflict in each DEC file.
618 self
._CheckAllPcdsTokenValueConflict
()
621 # Check PCD type and definition between DSC and DEC
623 self
._CheckPcdDefineAndType
()
626 # self._CheckDuplicateInFV(Fdf)
628 self
._BuildDir
= None
630 self
._MakeFileDir
= None
631 self
._BuildCommand
= None
635 def _BuildOptionPcdValueFormat(self
, TokenSpaceGuidCName
, TokenCName
, PcdDatumType
, Value
):
636 if PcdDatumType
== 'VOID*':
637 if Value
.startswith('L'):
639 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"{...}"')
640 Value
= Value
[0] + '"' + Value
[1:] + '"'
641 elif Value
.startswith('B'):
643 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"{...}"')
647 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"{...}"')
648 Value
= '"' + Value
+ '"'
650 IsValid
, Cause
= CheckPcdDatum(PcdDatumType
, Value
)
652 EdkLogger
.error('build', FORMAT_INVALID
, Cause
, ExtraData
="%s.%s" % (TokenSpaceGuidCName
, TokenCName
))
653 if PcdDatumType
== 'BOOLEAN':
654 Value
= Value
.upper()
655 if Value
== 'TRUE' or Value
== '1':
657 elif Value
== 'FALSE' or Value
== '0':
661 ## _CheckDuplicateInFV() method
663 # Check whether there is duplicate modules/files exist in FV section.
664 # The check base on the file GUID;
666 def _CheckDuplicateInFV(self
, Fdf
):
667 for Fv
in Fdf
.Profile
.FvDict
:
669 for FfsFile
in Fdf
.Profile
.FvDict
[Fv
].FfsList
:
670 if FfsFile
.InfFileName
and FfsFile
.NameGuid
== None:
675 for Pa
in self
.AutoGenObjectList
:
678 for Module
in Pa
.ModuleAutoGenList
:
679 if path
.normpath(Module
.MetaFile
.File
) == path
.normpath(FfsFile
.InfFileName
):
681 if not Module
.Guid
.upper() in _GuidDict
.keys():
682 _GuidDict
[Module
.Guid
.upper()] = FfsFile
685 EdkLogger
.error("build",
687 "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile
.CurrentLineNum
,
688 FfsFile
.CurrentLineContent
,
689 _GuidDict
[Module
.Guid
.upper()].CurrentLineNum
,
690 _GuidDict
[Module
.Guid
.upper()].CurrentLineContent
,
691 Module
.Guid
.upper()),
692 ExtraData
=self
.FdfFile
)
694 # Some INF files not have entity in DSC file.
697 if FfsFile
.InfFileName
.find('$') == -1:
698 InfPath
= NormPath(FfsFile
.InfFileName
)
699 if not os
.path
.exists(InfPath
):
700 EdkLogger
.error('build', GENFDS_ERROR
, "Non-existant Module %s !" % (FfsFile
.InfFileName
))
702 PathClassObj
= PathClass(FfsFile
.InfFileName
, self
.WorkspaceDir
)
704 # Here we just need to get FILE_GUID from INF file, use 'COMMON' as ARCH attribute. and use
705 # BuildObject from one of AutoGenObjectList is enough.
707 InfObj
= self
.AutoGenObjectList
[0].BuildDatabase
.WorkspaceDb
.BuildObject
[PathClassObj
, 'COMMON', self
.BuildTarget
, self
.ToolChain
]
708 if not InfObj
.Guid
.upper() in _GuidDict
.keys():
709 _GuidDict
[InfObj
.Guid
.upper()] = FfsFile
711 EdkLogger
.error("build",
713 "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile
.CurrentLineNum
,
714 FfsFile
.CurrentLineContent
,
715 _GuidDict
[InfObj
.Guid
.upper()].CurrentLineNum
,
716 _GuidDict
[InfObj
.Guid
.upper()].CurrentLineContent
,
717 InfObj
.Guid
.upper()),
718 ExtraData
=self
.FdfFile
)
721 if FfsFile
.NameGuid
!= None:
722 _CheckPCDAsGuidPattern
= re
.compile("^PCD\(.+\..+\)$")
725 # If the NameGuid reference a PCD name.
726 # The style must match: PCD(xxxx.yyy)
728 if _CheckPCDAsGuidPattern
.match(FfsFile
.NameGuid
):
730 # Replace the PCD value.
732 _PcdName
= FfsFile
.NameGuid
.lstrip("PCD(").rstrip(")")
734 for Pa
in self
.AutoGenObjectList
:
736 for PcdItem
in Pa
.AllPcdList
:
737 if (PcdItem
.TokenSpaceGuidCName
+ "." + PcdItem
.TokenCName
) == _PcdName
:
739 # First convert from CFormatGuid to GUID string
741 _PcdGuidString
= GuidStructureStringToGuidString(PcdItem
.DefaultValue
)
743 if not _PcdGuidString
:
745 # Then try Byte array.
747 _PcdGuidString
= GuidStructureByteArrayToGuidString(PcdItem
.DefaultValue
)
749 if not _PcdGuidString
:
751 # Not Byte array or CFormat GUID, raise error.
753 EdkLogger
.error("build",
755 "The format of PCD value is incorrect. PCD: %s , Value: %s\n" % (_PcdName
, PcdItem
.DefaultValue
),
756 ExtraData
=self
.FdfFile
)
758 if not _PcdGuidString
.upper() in _GuidDict
.keys():
759 _GuidDict
[_PcdGuidString
.upper()] = FfsFile
763 EdkLogger
.error("build",
765 "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile
.CurrentLineNum
,
766 FfsFile
.CurrentLineContent
,
767 _GuidDict
[_PcdGuidString
.upper()].CurrentLineNum
,
768 _GuidDict
[_PcdGuidString
.upper()].CurrentLineContent
,
769 FfsFile
.NameGuid
.upper()),
770 ExtraData
=self
.FdfFile
)
772 if not FfsFile
.NameGuid
.upper() in _GuidDict
.keys():
773 _GuidDict
[FfsFile
.NameGuid
.upper()] = FfsFile
776 # Two raw file GUID conflict.
778 EdkLogger
.error("build",
780 "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile
.CurrentLineNum
,
781 FfsFile
.CurrentLineContent
,
782 _GuidDict
[FfsFile
.NameGuid
.upper()].CurrentLineNum
,
783 _GuidDict
[FfsFile
.NameGuid
.upper()].CurrentLineContent
,
784 FfsFile
.NameGuid
.upper()),
785 ExtraData
=self
.FdfFile
)
788 def _CheckPcdDefineAndType(self
):
790 "FixedAtBuild", "PatchableInModule", "FeatureFlag",
791 "Dynamic", #"DynamicHii", "DynamicVpd",
792 "DynamicEx", # "DynamicExHii", "DynamicExVpd"
795 # This dict store PCDs which are not used by any modules with specified arches
797 for Pa
in self
.AutoGenObjectList
:
798 # Key of DSC's Pcds dictionary is PcdCName, TokenSpaceGuid
799 for Pcd
in Pa
.Platform
.Pcds
:
800 PcdType
= Pa
.Platform
.Pcds
[Pcd
].Type
802 # If no PCD type, this PCD comes from FDF
806 # Try to remove Hii and Vpd suffix
807 if PcdType
.startswith("DynamicEx"):
808 PcdType
= "DynamicEx"
809 elif PcdType
.startswith("Dynamic"):
812 for Package
in Pa
.PackageList
:
813 # Key of DEC's Pcds dictionary is PcdCName, TokenSpaceGuid, PcdType
814 if (Pcd
[0], Pcd
[1], PcdType
) in Package
.Pcds
:
816 for Type
in PcdTypeList
:
817 if (Pcd
[0], Pcd
[1], Type
) in Package
.Pcds
:
821 "Type [%s] of PCD [%s.%s] in DSC file doesn't match the type [%s] defined in DEC file." \
822 % (Pa
.Platform
.Pcds
[Pcd
].Type
, Pcd
[1], Pcd
[0], Type
),
827 UnusedPcd
.setdefault(Pcd
, []).append(Pa
.Arch
)
829 for Pcd
in UnusedPcd
:
832 "The PCD was not specified by any INF module in the platform for the given architecture.\n"
833 "\tPCD: [%s.%s]\n\tPlatform: [%s]\n\tArch: %s"
834 % (Pcd
[1], Pcd
[0], os
.path
.basename(str(self
.MetaFile
)), str(UnusedPcd
[Pcd
])),
839 return "%s [%s]" % (self
.MetaFile
, ", ".join(self
.ArchList
))
841 ## Return the directory to store FV files
843 if self
._FvDir
== None:
844 self
._FvDir
= path
.join(self
.BuildDir
, 'FV')
847 ## Return the directory to store all intermediate and final files built
848 def _GetBuildDir(self
):
849 return self
.AutoGenObjectList
[0].BuildDir
851 ## Return the build output directory platform specifies
852 def _GetOutputDir(self
):
853 return self
.Platform
.OutputDirectory
855 ## Return platform name
857 return self
.Platform
.PlatformName
859 ## Return meta-file GUID
861 return self
.Platform
.Guid
863 ## Return platform version
864 def _GetVersion(self
):
865 return self
.Platform
.Version
867 ## Return paths of tools
868 def _GetToolDefinition(self
):
869 return self
.AutoGenObjectList
[0].ToolDefinition
871 ## Return directory of platform makefile
873 # @retval string Makefile directory
875 def _GetMakeFileDir(self
):
876 if self
._MakeFileDir
== None:
877 self
._MakeFileDir
= self
.BuildDir
878 return self
._MakeFileDir
880 ## Return build command string
882 # @retval string Build command string
884 def _GetBuildCommand(self
):
885 if self
._BuildCommand
== None:
886 # BuildCommand should be all the same. So just get one from platform AutoGen
887 self
._BuildCommand
= self
.AutoGenObjectList
[0].BuildCommand
888 return self
._BuildCommand
890 ## Check the PCDs token value conflict in each DEC file.
892 # Will cause build break and raise error message while two PCDs conflict.
896 def _CheckAllPcdsTokenValueConflict(self
):
897 for Pa
in self
.AutoGenObjectList
:
898 for Package
in Pa
.PackageList
:
899 PcdList
= Package
.Pcds
.values()
900 PcdList
.sort(lambda x
, y
: cmp(int(x
.TokenValue
, 0), int(y
.TokenValue
, 0)))
902 while (Count
< len(PcdList
) - 1) :
903 Item
= PcdList
[Count
]
904 ItemNext
= PcdList
[Count
+ 1]
906 # Make sure in the same token space the TokenValue should be unique
908 if (int(Item
.TokenValue
, 0) == int(ItemNext
.TokenValue
, 0)):
909 SameTokenValuePcdList
= []
910 SameTokenValuePcdList
.append(Item
)
911 SameTokenValuePcdList
.append(ItemNext
)
912 RemainPcdListLength
= len(PcdList
) - Count
- 2
913 for ValueSameCount
in range(RemainPcdListLength
):
914 if int(PcdList
[len(PcdList
) - RemainPcdListLength
+ ValueSameCount
].TokenValue
, 0) == int(Item
.TokenValue
, 0):
915 SameTokenValuePcdList
.append(PcdList
[len(PcdList
) - RemainPcdListLength
+ ValueSameCount
])
919 # Sort same token value PCD list with TokenGuid and TokenCName
921 SameTokenValuePcdList
.sort(lambda x
, y
: cmp("%s.%s" % (x
.TokenSpaceGuidCName
, x
.TokenCName
), "%s.%s" % (y
.TokenSpaceGuidCName
, y
.TokenCName
)))
922 SameTokenValuePcdListCount
= 0
923 while (SameTokenValuePcdListCount
< len(SameTokenValuePcdList
) - 1):
925 TemListItem
= SameTokenValuePcdList
[SameTokenValuePcdListCount
]
926 TemListItemNext
= SameTokenValuePcdList
[SameTokenValuePcdListCount
+ 1]
928 if (TemListItem
.TokenSpaceGuidCName
== TemListItemNext
.TokenSpaceGuidCName
) and (TemListItem
.TokenCName
!= TemListItemNext
.TokenCName
):
929 for PcdItem
in GlobalData
.MixedPcd
:
930 if (TemListItem
.TokenCName
, TemListItem
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
] or \
931 (TemListItemNext
.TokenCName
, TemListItemNext
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
937 "The TokenValue [%s] of PCD [%s.%s] is conflict with: [%s.%s] in %s"\
938 % (TemListItem
.TokenValue
, TemListItem
.TokenSpaceGuidCName
, TemListItem
.TokenCName
, TemListItemNext
.TokenSpaceGuidCName
, TemListItemNext
.TokenCName
, Package
),
941 SameTokenValuePcdListCount
+= 1
942 Count
+= SameTokenValuePcdListCount
945 PcdList
= Package
.Pcds
.values()
946 PcdList
.sort(lambda x
, y
: cmp("%s.%s" % (x
.TokenSpaceGuidCName
, x
.TokenCName
), "%s.%s" % (y
.TokenSpaceGuidCName
, y
.TokenCName
)))
948 while (Count
< len(PcdList
) - 1) :
949 Item
= PcdList
[Count
]
950 ItemNext
= PcdList
[Count
+ 1]
952 # Check PCDs with same TokenSpaceGuidCName.TokenCName have same token value as well.
954 if (Item
.TokenSpaceGuidCName
== ItemNext
.TokenSpaceGuidCName
) and (Item
.TokenCName
== ItemNext
.TokenCName
) and (int(Item
.TokenValue
, 0) != int(ItemNext
.TokenValue
, 0)):
958 "The TokenValue [%s] of PCD [%s.%s] in %s defined in two places should be same as well."\
959 % (Item
.TokenValue
, Item
.TokenSpaceGuidCName
, Item
.TokenCName
, Package
),
963 ## Generate fds command
964 def _GenFdsCommand(self
):
965 return (GenMake
.TopLevelMakefile(self
)._TEMPLATE
_.Replace(GenMake
.TopLevelMakefile(self
)._TemplateDict
)).strip()
967 ## Create makefile for the platform and modules in it
969 # @param CreateDepsMakeFile Flag indicating if the makefile for
970 # modules will be created as well
972 def CreateMakeFile(self
, CreateDepsMakeFile
=False):
973 if CreateDepsMakeFile
:
974 for Pa
in self
.AutoGenObjectList
:
975 Pa
.CreateMakeFile(CreateDepsMakeFile
)
977 ## Create autogen code for platform and modules
979 # Since there's no autogen code for platform, this method will do nothing
980 # if CreateModuleCodeFile is set to False.
982 # @param CreateDepsCodeFile Flag indicating if creating module's
983 # autogen code file or not
985 def CreateCodeFile(self
, CreateDepsCodeFile
=False):
986 if not CreateDepsCodeFile
:
988 for Pa
in self
.AutoGenObjectList
:
989 Pa
.CreateCodeFile(CreateDepsCodeFile
)
991 ## Create AsBuilt INF file the platform
993 def CreateAsBuiltInf(self
):
996 Name
= property(_GetName
)
997 Guid
= property(_GetGuid
)
998 Version
= property(_GetVersion
)
999 OutputDir
= property(_GetOutputDir
)
1001 ToolDefinition
= property(_GetToolDefinition
) # toolcode : tool path
1003 BuildDir
= property(_GetBuildDir
)
1004 FvDir
= property(_GetFvDir
)
1005 MakeFileDir
= property(_GetMakeFileDir
)
1006 BuildCommand
= property(_GetBuildCommand
)
1007 GenFdsCommand
= property(_GenFdsCommand
)
1009 ## AutoGen class for platform
1011 # PlatformAutoGen class will process the original information in platform
1012 # file in order to generate makefile for platform.
1014 class PlatformAutoGen(AutoGen
):
1016 # Used to store all PCDs for both PEI and DXE phase, in order to generate
1017 # correct PCD database
1020 _NonDynaPcdList_
= []
1024 # The priority list while override build option
1026 PrioList
= {"0x11111" : 16, # TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE (Highest)
1027 "0x01111" : 15, # ******_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
1028 "0x10111" : 14, # TARGET_*********_ARCH_COMMANDTYPE_ATTRIBUTE
1029 "0x00111" : 13, # ******_*********_ARCH_COMMANDTYPE_ATTRIBUTE
1030 "0x11011" : 12, # TARGET_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE
1031 "0x01011" : 11, # ******_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE
1032 "0x10011" : 10, # TARGET_*********_****_COMMANDTYPE_ATTRIBUTE
1033 "0x00011" : 9, # ******_*********_****_COMMANDTYPE_ATTRIBUTE
1034 "0x11101" : 8, # TARGET_TOOLCHAIN_ARCH_***********_ATTRIBUTE
1035 "0x01101" : 7, # ******_TOOLCHAIN_ARCH_***********_ATTRIBUTE
1036 "0x10101" : 6, # TARGET_*********_ARCH_***********_ATTRIBUTE
1037 "0x00101" : 5, # ******_*********_ARCH_***********_ATTRIBUTE
1038 "0x11001" : 4, # TARGET_TOOLCHAIN_****_***********_ATTRIBUTE
1039 "0x01001" : 3, # ******_TOOLCHAIN_****_***********_ATTRIBUTE
1040 "0x10001" : 2, # TARGET_*********_****_***********_ATTRIBUTE
1041 "0x00001" : 1} # ******_*********_****_***********_ATTRIBUTE (Lowest)
1043 ## The real constructor of PlatformAutoGen
1045 # This method is not supposed to be called by users of PlatformAutoGen. It's
1046 # only used by factory method __new__() to do real initialization work for an
1047 # object of PlatformAutoGen
1049 # @param Workspace WorkspaceAutoGen object
1050 # @param PlatformFile Platform file (DSC file)
1051 # @param Target Build target (DEBUG, RELEASE)
1052 # @param Toolchain Name of tool chain
1053 # @param Arch arch of the platform supports
1055 def _Init(self
, Workspace
, PlatformFile
, Target
, Toolchain
, Arch
):
1056 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "AutoGen platform [%s] [%s]" % (PlatformFile
, Arch
))
1057 GlobalData
.gProcessingFile
= "%s [%s, %s, %s]" % (PlatformFile
, Arch
, Toolchain
, Target
)
1059 self
.MetaFile
= PlatformFile
1060 self
.Workspace
= Workspace
1061 self
.WorkspaceDir
= Workspace
.WorkspaceDir
1062 self
.ToolChain
= Toolchain
1063 self
.BuildTarget
= Target
1065 self
.SourceDir
= PlatformFile
.SubDir
1066 self
.SourceOverrideDir
= None
1067 self
.FdTargetList
= self
.Workspace
.FdTargetList
1068 self
.FvTargetList
= self
.Workspace
.FvTargetList
1069 self
.AllPcdList
= []
1070 # get the original module/package/platform objects
1071 self
.BuildDatabase
= Workspace
.BuildDatabase
1073 # flag indicating if the makefile/C-code file has been created or not
1074 self
.IsMakeFileCreated
= False
1075 self
.IsCodeFileCreated
= False
1077 self
._Platform
= None
1080 self
._Version
= None
1082 self
._BuildRule
= None
1083 self
._SourceDir
= None
1084 self
._BuildDir
= None
1085 self
._OutputDir
= None
1087 self
._MakeFileDir
= None
1088 self
._FdfFile
= None
1090 self
._PcdTokenNumber
= None # (TokenCName, TokenSpaceGuidCName) : GeneratedTokenNumber
1091 self
._DynamicPcdList
= None # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
1092 self
._NonDynamicPcdList
= None # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
1093 self
._NonDynamicPcdDict
= {}
1095 self
._ToolDefinitions
= None
1096 self
._ToolDefFile
= None # toolcode : tool path
1097 self
._ToolChainFamily
= None
1098 self
._BuildRuleFamily
= None
1099 self
._BuildOption
= None # toolcode : option
1100 self
._EdkBuildOption
= None # edktoolcode : option
1101 self
._EdkIIBuildOption
= None # edkiitoolcode : option
1102 self
._PackageList
= None
1103 self
._ModuleAutoGenList
= None
1104 self
._LibraryAutoGenList
= None
1105 self
._BuildCommand
= None
1106 self
._AsBuildInfList
= []
1107 self
._AsBuildModuleList
= []
1108 if GlobalData
.gFdfParser
!= None:
1109 self
._AsBuildInfList
= GlobalData
.gFdfParser
.Profile
.InfList
1110 for Inf
in self
._AsBuildInfList
:
1111 InfClass
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, self
.Arch
)
1112 M
= self
.BuildDatabase
[InfClass
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1113 if not M
.IsSupportedArch
:
1115 self
._AsBuildModuleList
.append(InfClass
)
1116 # get library/modules for build
1117 self
.LibraryBuildDirectoryList
= []
1118 self
.ModuleBuildDirectoryList
= []
1122 return "%s [%s]" % (self
.MetaFile
, self
.Arch
)
1124 ## Create autogen code for platform and modules
1126 # Since there's no autogen code for platform, this method will do nothing
1127 # if CreateModuleCodeFile is set to False.
1129 # @param CreateModuleCodeFile Flag indicating if creating module's
1130 # autogen code file or not
1132 def CreateCodeFile(self
, CreateModuleCodeFile
=False):
1133 # only module has code to be greated, so do nothing if CreateModuleCodeFile is False
1134 if self
.IsCodeFileCreated
or not CreateModuleCodeFile
:
1137 for Ma
in self
.ModuleAutoGenList
:
1138 Ma
.CreateCodeFile(True)
1140 # don't do this twice
1141 self
.IsCodeFileCreated
= True
1143 ## Generate Fds Command
1144 def _GenFdsCommand(self
):
1145 return self
.Workspace
.GenFdsCommand
1147 ## Create makefile for the platform and mdoules in it
1149 # @param CreateModuleMakeFile Flag indicating if the makefile for
1150 # modules will be created as well
1152 def CreateMakeFile(self
, CreateModuleMakeFile
=False):
1153 if CreateModuleMakeFile
:
1154 for ModuleFile
in self
.Platform
.Modules
:
1155 Ma
= ModuleAutoGen(self
.Workspace
, ModuleFile
, self
.BuildTarget
,
1156 self
.ToolChain
, self
.Arch
, self
.MetaFile
)
1157 Ma
.CreateMakeFile(True)
1158 #Ma.CreateAsBuiltInf()
1160 # no need to create makefile for the platform more than once
1161 if self
.IsMakeFileCreated
:
1164 # create library/module build dirs for platform
1165 Makefile
= GenMake
.PlatformMakefile(self
)
1166 self
.LibraryBuildDirectoryList
= Makefile
.GetLibraryBuildDirectoryList()
1167 self
.ModuleBuildDirectoryList
= Makefile
.GetModuleBuildDirectoryList()
1169 self
.IsMakeFileCreated
= True
1171 ## Deal with Shared FixedAtBuild Pcds
1173 def CollectFixedAtBuildPcds(self
):
1174 for LibAuto
in self
.LibraryAutoGenList
:
1175 FixedAtBuildPcds
= {}
1176 ShareFixedAtBuildPcdsSameValue
= {}
1177 for Module
in LibAuto
._ReferenceModules
:
1178 for Pcd
in Module
.FixedAtBuildPcds
+ LibAuto
.FixedAtBuildPcds
:
1179 key
= ".".join((Pcd
.TokenSpaceGuidCName
,Pcd
.TokenCName
))
1180 if key
not in FixedAtBuildPcds
:
1181 ShareFixedAtBuildPcdsSameValue
[key
] = True
1182 FixedAtBuildPcds
[key
] = Pcd
.DefaultValue
1184 if FixedAtBuildPcds
[key
] != Pcd
.DefaultValue
:
1185 ShareFixedAtBuildPcdsSameValue
[key
] = False
1186 for Pcd
in LibAuto
.FixedAtBuildPcds
:
1187 key
= ".".join((Pcd
.TokenSpaceGuidCName
,Pcd
.TokenCName
))
1188 if (Pcd
.TokenCName
,Pcd
.TokenSpaceGuidCName
) not in self
.NonDynamicPcdDict
:
1191 DscPcd
= self
.NonDynamicPcdDict
[(Pcd
.TokenCName
,Pcd
.TokenSpaceGuidCName
)]
1192 if DscPcd
.Type
!= "FixedAtBuild":
1194 if key
in ShareFixedAtBuildPcdsSameValue
and ShareFixedAtBuildPcdsSameValue
[key
]:
1195 LibAuto
.ConstPcd
[key
] = Pcd
.DefaultValue
1197 ## Collect dynamic PCDs
1199 # Gather dynamic PCDs list from each module and their settings from platform
1200 # This interface should be invoked explicitly when platform action is created.
1202 def CollectPlatformDynamicPcds(self
):
1203 # Override the platform Pcd's value by build option
1204 if GlobalData
.BuildOptionPcd
:
1205 for key
in self
.Platform
.Pcds
:
1206 PlatformPcd
= self
.Platform
.Pcds
[key
]
1207 for PcdItem
in GlobalData
.BuildOptionPcd
:
1208 if (PlatformPcd
.TokenSpaceGuidCName
, PlatformPcd
.TokenCName
) == (PcdItem
[0], PcdItem
[1]):
1209 PlatformPcd
.DefaultValue
= PcdItem
[2]
1210 if PlatformPcd
.SkuInfoList
:
1211 Sku
= PlatformPcd
.SkuInfoList
[PlatformPcd
.SkuInfoList
.keys()[0]]
1212 Sku
.DefaultValue
= PcdItem
[2]
1215 for key
in self
.Platform
.Pcds
:
1216 for SinglePcd
in GlobalData
.MixedPcd
:
1217 if (self
.Platform
.Pcds
[key
].TokenCName
, self
.Platform
.Pcds
[key
].TokenSpaceGuidCName
) == SinglePcd
:
1218 for item
in GlobalData
.MixedPcd
[SinglePcd
]:
1219 Pcd_Type
= item
[0].split('_')[-1]
1220 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 \
1221 (Pcd_Type
== TAB_PCDS_DYNAMIC
and self
.Platform
.Pcds
[key
].Type
in GenC
.gDynamicPcd
):
1222 Value
= self
.Platform
.Pcds
[key
]
1223 Value
.TokenCName
= self
.Platform
.Pcds
[key
].TokenCName
+ '_' + Pcd_Type
1225 newkey
= (Value
.TokenCName
, key
[1])
1227 newkey
= (Value
.TokenCName
, key
[1], key
[2])
1228 del self
.Platform
.Pcds
[key
]
1229 self
.Platform
.Pcds
[newkey
] = Value
1237 # for gathering error information
1238 NoDatumTypePcdList
= set()
1240 self
._GuidValue
= {}
1242 for InfName
in self
._AsBuildInfList
:
1243 InfName
= mws
.join(self
.WorkspaceDir
, InfName
)
1244 FdfModuleList
.append(os
.path
.normpath(InfName
))
1245 for F
in self
.Platform
.Modules
.keys():
1246 M
= ModuleAutoGen(self
.Workspace
, F
, self
.BuildTarget
, self
.ToolChain
, self
.Arch
, self
.MetaFile
)
1247 #GuidValue.update(M.Guids)
1249 self
.Platform
.Modules
[F
].M
= M
1251 for PcdFromModule
in M
.ModulePcdList
+ M
.LibraryPcdList
:
1252 # make sure that the "VOID*" kind of datum has MaxDatumSize set
1253 if PcdFromModule
.DatumType
== "VOID*" and PcdFromModule
.MaxDatumSize
in [None, '']:
1254 NoDatumTypePcdList
.add("%s.%s [%s]" % (PcdFromModule
.TokenSpaceGuidCName
, PcdFromModule
.TokenCName
, F
))
1256 # Check the PCD from Binary INF or Source INF
1257 if M
.IsBinaryModule
== True:
1258 PcdFromModule
.IsFromBinaryInf
= True
1260 # Check the PCD from DSC or not
1261 if (PcdFromModule
.TokenCName
, PcdFromModule
.TokenSpaceGuidCName
) in self
.Platform
.Pcds
.keys():
1262 PcdFromModule
.IsFromDsc
= True
1264 PcdFromModule
.IsFromDsc
= False
1265 if PcdFromModule
.Type
in GenC
.gDynamicPcd
or PcdFromModule
.Type
in GenC
.gDynamicExPcd
:
1266 if F
.Path
not in FdfModuleList
:
1267 # If one of the Source built modules listed in the DSC is not listed
1268 # in FDF modules, and the INF lists a PCD can only use the PcdsDynamic
1269 # access method (it is only listed in the DEC file that declares the
1270 # PCD as PcdsDynamic), then build tool will report warning message
1271 # notify the PI that they are attempting to build a module that must
1272 # be included in a flash image in order to be functional. These Dynamic
1273 # PCD will not be added into the Database unless it is used by other
1274 # modules that are included in the FDF file.
1275 if PcdFromModule
.Type
in GenC
.gDynamicPcd
and \
1276 PcdFromModule
.IsFromBinaryInf
== False:
1277 # Print warning message to let the developer make a determine.
1278 if PcdFromModule
not in PcdNotInDb
:
1279 PcdNotInDb
.append(PcdFromModule
)
1281 # If one of the Source built modules listed in the DSC is not listed in
1282 # FDF modules, and the INF lists a PCD can only use the PcdsDynamicEx
1283 # access method (it is only listed in the DEC file that declares the
1284 # PCD as PcdsDynamicEx), then DO NOT break the build; DO NOT add the
1285 # PCD to the Platform's PCD Database.
1286 if PcdFromModule
.Type
in GenC
.gDynamicExPcd
:
1287 if PcdFromModule
not in PcdNotInDb
:
1288 PcdNotInDb
.append(PcdFromModule
)
1291 # If a dynamic PCD used by a PEM module/PEI module & DXE module,
1292 # it should be stored in Pcd PEI database, If a dynamic only
1293 # used by DXE module, it should be stored in DXE PCD database.
1294 # The default Phase is DXE
1296 if M
.ModuleType
in ["PEIM", "PEI_CORE"]:
1297 PcdFromModule
.Phase
= "PEI"
1298 if PcdFromModule
not in self
._DynaPcdList
_:
1299 self
._DynaPcdList
_.append(PcdFromModule
)
1300 elif PcdFromModule
.Phase
== 'PEI':
1301 # overwrite any the same PCD existing, if Phase is PEI
1302 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1303 self
._DynaPcdList
_[Index
] = PcdFromModule
1304 elif PcdFromModule
not in self
._NonDynaPcdList
_:
1305 self
._NonDynaPcdList
_.append(PcdFromModule
)
1306 elif PcdFromModule
in self
._NonDynaPcdList
_ and PcdFromModule
.IsFromBinaryInf
== True:
1307 Index
= self
._NonDynaPcdList
_.index(PcdFromModule
)
1308 if self
._NonDynaPcdList
_[Index
].IsFromBinaryInf
== False:
1309 #The PCD from Binary INF will override the same one from source INF
1310 self
._NonDynaPcdList
_.remove (self
._NonDynaPcdList
_[Index
])
1311 PcdFromModule
.Pending
= False
1312 self
._NonDynaPcdList
_.append (PcdFromModule
)
1313 # Parse the DynamicEx PCD from the AsBuild INF module list of FDF.
1315 for ModuleInf
in self
.Platform
.Modules
.keys():
1316 DscModuleList
.append (os
.path
.normpath(ModuleInf
.Path
))
1317 # add the PCD from modules that listed in FDF but not in DSC to Database
1318 for InfName
in FdfModuleList
:
1319 if InfName
not in DscModuleList
:
1320 InfClass
= PathClass(InfName
)
1321 M
= self
.BuildDatabase
[InfClass
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1322 # If a module INF in FDF but not in current arch's DSC module list, it must be module (either binary or source)
1323 # for different Arch. PCDs in source module for different Arch is already added before, so skip the source module here.
1324 # For binary module, if in current arch, we need to list the PCDs into database.
1325 if not M
.IsSupportedArch
:
1327 # Override the module PCD setting by platform setting
1328 ModulePcdList
= self
.ApplyPcdSetting(M
, M
.Pcds
)
1329 for PcdFromModule
in ModulePcdList
:
1330 PcdFromModule
.IsFromBinaryInf
= True
1331 PcdFromModule
.IsFromDsc
= False
1332 # Only allow the DynamicEx and Patchable PCD in AsBuild INF
1333 if PcdFromModule
.Type
not in GenC
.gDynamicExPcd
and PcdFromModule
.Type
not in TAB_PCDS_PATCHABLE_IN_MODULE
:
1334 EdkLogger
.error("build", AUTOGEN_ERROR
, "PCD setting error",
1336 ExtraData
="\n\tExisted %s PCD %s in:\n\t\t%s\n"
1337 % (PcdFromModule
.Type
, PcdFromModule
.TokenCName
, InfName
))
1338 # make sure that the "VOID*" kind of datum has MaxDatumSize set
1339 if PcdFromModule
.DatumType
== "VOID*" and PcdFromModule
.MaxDatumSize
in [None, '']:
1340 NoDatumTypePcdList
.add("%s.%s [%s]" % (PcdFromModule
.TokenSpaceGuidCName
, PcdFromModule
.TokenCName
, InfName
))
1341 if M
.ModuleType
in ["PEIM", "PEI_CORE"]:
1342 PcdFromModule
.Phase
= "PEI"
1343 if PcdFromModule
not in self
._DynaPcdList
_ and PcdFromModule
.Type
in GenC
.gDynamicExPcd
:
1344 self
._DynaPcdList
_.append(PcdFromModule
)
1345 elif PcdFromModule
not in self
._NonDynaPcdList
_ and PcdFromModule
.Type
in TAB_PCDS_PATCHABLE_IN_MODULE
:
1346 self
._NonDynaPcdList
_.append(PcdFromModule
)
1347 if PcdFromModule
in self
._DynaPcdList
_ and PcdFromModule
.Phase
== 'PEI' and PcdFromModule
.Type
in GenC
.gDynamicExPcd
:
1348 # Overwrite the phase of any the same PCD existing, if Phase is PEI.
1349 # It is to solve the case that a dynamic PCD used by a PEM module/PEI
1350 # module & DXE module at a same time.
1351 # Overwrite the type of the PCDs in source INF by the type of AsBuild
1352 # INF file as DynamicEx.
1353 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1354 self
._DynaPcdList
_[Index
].Phase
= PcdFromModule
.Phase
1355 self
._DynaPcdList
_[Index
].Type
= PcdFromModule
.Type
1356 for PcdFromModule
in self
._NonDynaPcdList
_:
1357 # If a PCD is not listed in the DSC file, but binary INF files used by
1358 # this platform all (that use this PCD) list the PCD in a [PatchPcds]
1359 # section, AND all source INF files used by this platform the build
1360 # that use the PCD list the PCD in either a [Pcds] or [PatchPcds]
1361 # section, then the tools must NOT add the PCD to the Platform's PCD
1362 # Database; the build must assign the access method for this PCD as
1363 # PcdsPatchableInModule.
1364 if PcdFromModule
not in self
._DynaPcdList
_:
1366 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1367 if PcdFromModule
.IsFromDsc
== False and \
1368 PcdFromModule
.Type
in TAB_PCDS_PATCHABLE_IN_MODULE
and \
1369 PcdFromModule
.IsFromBinaryInf
== True and \
1370 self
._DynaPcdList
_[Index
].IsFromBinaryInf
== False:
1371 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1372 self
._DynaPcdList
_.remove (self
._DynaPcdList
_[Index
])
1374 # print out error information and break the build, if error found
1375 if len(NoDatumTypePcdList
) > 0:
1376 NoDatumTypePcdListString
= "\n\t\t".join(NoDatumTypePcdList
)
1377 EdkLogger
.error("build", AUTOGEN_ERROR
, "PCD setting error",
1379 ExtraData
="\n\tPCD(s) without MaxDatumSize:\n\t\t%s\n"
1380 % NoDatumTypePcdListString
)
1381 self
._NonDynamicPcdList
= self
._NonDynaPcdList
_
1382 self
._DynamicPcdList
= self
._DynaPcdList
_
1384 # Sort dynamic PCD list to:
1385 # 1) If PCD's datum type is VOID* and value is unicode string which starts with L, the PCD item should
1386 # try to be put header of dynamicd List
1387 # 2) If PCD is HII type, the PCD item should be put after unicode type PCD
1389 # The reason of sorting is make sure the unicode string is in double-byte alignment in string table.
1391 UnicodePcdArray
= []
1395 VpdFile
= VpdInfoFile
.VpdInfoFile()
1396 NeedProcessVpdMapFile
= False
1398 for pcd
in self
.Platform
.Pcds
.keys():
1399 if pcd
not in self
._PlatformPcds
.keys():
1400 self
._PlatformPcds
[pcd
] = self
.Platform
.Pcds
[pcd
]
1402 if (self
.Workspace
.ArchList
[-1] == self
.Arch
):
1403 for Pcd
in self
._DynamicPcdList
:
1404 # just pick the a value to determine whether is unicode string type
1405 Sku
= Pcd
.SkuInfoList
[Pcd
.SkuInfoList
.keys()[0]]
1406 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1408 PcdValue
= Sku
.DefaultValue
1409 if Pcd
.DatumType
== 'VOID*' and PcdValue
.startswith("L"):
1410 # if found PCD which datum value is unicode string the insert to left size of UnicodeIndex
1411 UnicodePcdArray
.append(Pcd
)
1412 elif len(Sku
.VariableName
) > 0:
1413 # if found HII type PCD then insert to right of UnicodeIndex
1414 HiiPcdArray
.append(Pcd
)
1416 OtherPcdArray
.append(Pcd
)
1417 if Pcd
.Type
in [TAB_PCDS_DYNAMIC_VPD
, TAB_PCDS_DYNAMIC_EX_VPD
]:
1418 VpdPcdDict
[(Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
)] = Pcd
1420 PlatformPcds
= self
._PlatformPcds
.keys()
1423 # Add VPD type PCD into VpdFile and determine whether the VPD PCD need to be fixed up.
1425 for PcdKey
in PlatformPcds
:
1426 Pcd
= self
._PlatformPcds
[PcdKey
]
1427 if Pcd
.Type
in [TAB_PCDS_DYNAMIC_VPD
, TAB_PCDS_DYNAMIC_EX_VPD
] and \
1428 PcdKey
in VpdPcdDict
:
1429 Pcd
= VpdPcdDict
[PcdKey
]
1430 for (SkuName
,Sku
) in Pcd
.SkuInfoList
.items():
1431 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1432 PcdValue
= Sku
.DefaultValue
1434 PcdValue
= Pcd
.DefaultValue
1435 if Sku
.VpdOffset
!= '*':
1436 if PcdValue
.startswith("{"):
1438 elif PcdValue
.startswith("L"):
1443 VpdOffset
= int(Sku
.VpdOffset
)
1446 VpdOffset
= int(Sku
.VpdOffset
, 16)
1448 EdkLogger
.error("build", FORMAT_INVALID
, "Invalid offset value %s for PCD %s.%s." % (Sku
.VpdOffset
, Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
))
1449 if VpdOffset
% Alignment
!= 0:
1450 if PcdValue
.startswith("{"):
1451 EdkLogger
.warn("build", "The offset value of PCD %s.%s is not 8-byte aligned!" %(Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
), File
=self
.MetaFile
)
1453 EdkLogger
.error("build", FORMAT_INVALID
, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
, Alignment
))
1454 VpdFile
.Add(Pcd
, Sku
.VpdOffset
)
1455 # if the offset of a VPD is *, then it need to be fixed up by third party tool.
1456 if not NeedProcessVpdMapFile
and Sku
.VpdOffset
== "*":
1457 NeedProcessVpdMapFile
= True
1458 if self
.Platform
.VpdToolGuid
== None or self
.Platform
.VpdToolGuid
== '':
1459 EdkLogger
.error("Build", FILE_NOT_FOUND
, \
1460 "Fail to find third-party BPDG tool to process VPD PCDs. BPDG Guid tool need to be defined in tools_def.txt and VPD_TOOL_GUID need to be provided in DSC file.")
1464 # Fix the PCDs define in VPD PCD section that never referenced by module.
1465 # An example is PCD for signature usage.
1467 for DscPcd
in PlatformPcds
:
1468 DscPcdEntry
= self
._PlatformPcds
[DscPcd
]
1469 if DscPcdEntry
.Type
in [TAB_PCDS_DYNAMIC_VPD
, TAB_PCDS_DYNAMIC_EX_VPD
]:
1470 if not (self
.Platform
.VpdToolGuid
== None or self
.Platform
.VpdToolGuid
== ''):
1472 for VpdPcd
in VpdFile
._VpdArray
.keys():
1473 # This PCD has been referenced by module
1474 if (VpdPcd
.TokenSpaceGuidCName
== DscPcdEntry
.TokenSpaceGuidCName
) and \
1475 (VpdPcd
.TokenCName
== DscPcdEntry
.TokenCName
):
1478 # Not found, it should be signature
1480 # just pick the a value to determine whether is unicode string type
1481 for (SkuName
,Sku
) in DscPcdEntry
.SkuInfoList
.items():
1482 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1484 # Need to iterate DEC pcd information to get the value & datumtype
1485 for eachDec
in self
.PackageList
:
1486 for DecPcd
in eachDec
.Pcds
:
1487 DecPcdEntry
= eachDec
.Pcds
[DecPcd
]
1488 if (DecPcdEntry
.TokenSpaceGuidCName
== DscPcdEntry
.TokenSpaceGuidCName
) and \
1489 (DecPcdEntry
.TokenCName
== DscPcdEntry
.TokenCName
):
1490 # Print warning message to let the developer make a determine.
1491 EdkLogger
.warn("build", "Unreferenced vpd pcd used!",
1492 File
=self
.MetaFile
, \
1493 ExtraData
= "PCD: %s.%s used in the DSC file %s is unreferenced." \
1494 %(DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
, self
.Platform
.MetaFile
.Path
))
1496 DscPcdEntry
.DatumType
= DecPcdEntry
.DatumType
1497 DscPcdEntry
.DefaultValue
= DecPcdEntry
.DefaultValue
1498 DscPcdEntry
.TokenValue
= DecPcdEntry
.TokenValue
1499 DscPcdEntry
.TokenSpaceGuidValue
= eachDec
.Guids
[DecPcdEntry
.TokenSpaceGuidCName
]
1500 # Only fix the value while no value provided in DSC file.
1501 if (Sku
.DefaultValue
== "" or Sku
.DefaultValue
==None):
1502 DscPcdEntry
.SkuInfoList
[DscPcdEntry
.SkuInfoList
.keys()[0]].DefaultValue
= DecPcdEntry
.DefaultValue
1504 if DscPcdEntry
not in self
._DynamicPcdList
:
1505 self
._DynamicPcdList
.append(DscPcdEntry
)
1506 # Sku = DscPcdEntry.SkuInfoList[DscPcdEntry.SkuInfoList.keys()[0]]
1507 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1508 PcdValue
= Sku
.DefaultValue
1510 PcdValue
= DscPcdEntry
.DefaultValue
1511 if Sku
.VpdOffset
!= '*':
1512 if PcdValue
.startswith("{"):
1514 elif PcdValue
.startswith("L"):
1519 VpdOffset
= int(Sku
.VpdOffset
)
1522 VpdOffset
= int(Sku
.VpdOffset
, 16)
1524 EdkLogger
.error("build", FORMAT_INVALID
, "Invalid offset value %s for PCD %s.%s." % (Sku
.VpdOffset
, DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
))
1525 if VpdOffset
% Alignment
!= 0:
1526 if PcdValue
.startswith("{"):
1527 EdkLogger
.warn("build", "The offset value of PCD %s.%s is not 8-byte aligned!" %(DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
), File
=self
.MetaFile
)
1529 EdkLogger
.error("build", FORMAT_INVALID
, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
, Alignment
))
1530 VpdFile
.Add(DscPcdEntry
, Sku
.VpdOffset
)
1531 if not NeedProcessVpdMapFile
and Sku
.VpdOffset
== "*":
1532 NeedProcessVpdMapFile
= True
1533 if DscPcdEntry
.DatumType
== 'VOID*' and PcdValue
.startswith("L"):
1534 UnicodePcdArray
.append(DscPcdEntry
)
1535 elif len(Sku
.VariableName
) > 0:
1536 HiiPcdArray
.append(DscPcdEntry
)
1538 OtherPcdArray
.append(DscPcdEntry
)
1540 # if the offset of a VPD is *, then it need to be fixed up by third party tool.
1544 if (self
.Platform
.FlashDefinition
== None or self
.Platform
.FlashDefinition
== '') and \
1545 VpdFile
.GetCount() != 0:
1546 EdkLogger
.error("build", ATTRIBUTE_NOT_AVAILABLE
,
1547 "Fail to get FLASH_DEFINITION definition in DSC file %s which is required when DSC contains VPD PCD." % str(self
.Platform
.MetaFile
))
1549 if VpdFile
.GetCount() != 0:
1550 FvPath
= os
.path
.join(self
.BuildDir
, "FV")
1551 if not os
.path
.exists(FvPath
):
1555 EdkLogger
.error("build", FILE_WRITE_FAILURE
, "Fail to create FV folder under %s" % self
.BuildDir
)
1557 VpdFilePath
= os
.path
.join(FvPath
, "%s.txt" % self
.Platform
.VpdToolGuid
)
1559 if VpdFile
.Write(VpdFilePath
):
1560 # retrieve BPDG tool's path from tool_def.txt according to VPD_TOOL_GUID defined in DSC file.
1562 for ToolDef
in self
.ToolDefinition
.values():
1563 if ToolDef
.has_key("GUID") and ToolDef
["GUID"] == self
.Platform
.VpdToolGuid
:
1564 if not ToolDef
.has_key("PATH"):
1565 EdkLogger
.error("build", ATTRIBUTE_NOT_AVAILABLE
, "PATH attribute was not provided for BPDG guid tool %s in tools_def.txt" % self
.Platform
.VpdToolGuid
)
1566 BPDGToolName
= ToolDef
["PATH"]
1568 # Call third party GUID BPDG tool.
1569 if BPDGToolName
!= None:
1570 VpdInfoFile
.CallExtenalBPDGTool(BPDGToolName
, VpdFilePath
)
1572 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.")
1574 # Process VPD map file generated by third party BPDG tool
1575 if NeedProcessVpdMapFile
:
1576 VpdMapFilePath
= os
.path
.join(self
.BuildDir
, "FV", "%s.map" % self
.Platform
.VpdToolGuid
)
1577 if os
.path
.exists(VpdMapFilePath
):
1578 VpdFile
.Read(VpdMapFilePath
)
1581 for Pcd
in self
._DynamicPcdList
:
1582 # just pick the a value to determine whether is unicode string type
1584 for (SkuName
,Sku
) in Pcd
.SkuInfoList
.items():
1585 if Sku
.VpdOffset
== "*":
1586 Sku
.VpdOffset
= VpdFile
.GetOffset(Pcd
)[i
].strip()
1589 EdkLogger
.error("build", FILE_READ_FAILURE
, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath
)
1591 # Delete the DynamicPcdList At the last time enter into this function
1592 del self
._DynamicPcdList
[:]
1593 self
._DynamicPcdList
.extend(UnicodePcdArray
)
1594 self
._DynamicPcdList
.extend(HiiPcdArray
)
1595 self
._DynamicPcdList
.extend(OtherPcdArray
)
1596 self
.AllPcdList
= self
._NonDynamicPcdList
+ self
._DynamicPcdList
1598 ## Return the platform build data object
1599 def _GetPlatform(self
):
1600 if self
._Platform
== None:
1601 self
._Platform
= self
.BuildDatabase
[self
.MetaFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1602 return self
._Platform
1604 ## Return platform name
1606 return self
.Platform
.PlatformName
1608 ## Return the meta file GUID
1610 return self
.Platform
.Guid
1612 ## Return the platform version
1613 def _GetVersion(self
):
1614 return self
.Platform
.Version
1616 ## Return the FDF file name
1617 def _GetFdfFile(self
):
1618 if self
._FdfFile
== None:
1619 if self
.Workspace
.FdfFile
!= "":
1620 self
._FdfFile
= mws
.join(self
.WorkspaceDir
, self
.Workspace
.FdfFile
)
1623 return self
._FdfFile
1625 ## Return the build output directory platform specifies
1626 def _GetOutputDir(self
):
1627 return self
.Platform
.OutputDirectory
1629 ## Return the directory to store all intermediate and final files built
1630 def _GetBuildDir(self
):
1631 if self
._BuildDir
== None:
1632 if os
.path
.isabs(self
.OutputDir
):
1633 self
._BuildDir
= path
.join(
1634 path
.abspath(self
.OutputDir
),
1635 self
.BuildTarget
+ "_" + self
.ToolChain
,
1638 self
._BuildDir
= path
.join(
1641 self
.BuildTarget
+ "_" + self
.ToolChain
,
1643 return self
._BuildDir
1645 ## Return directory of platform makefile
1647 # @retval string Makefile directory
1649 def _GetMakeFileDir(self
):
1650 if self
._MakeFileDir
== None:
1651 self
._MakeFileDir
= path
.join(self
.BuildDir
, self
.Arch
)
1652 return self
._MakeFileDir
1654 ## Return build command string
1656 # @retval string Build command string
1658 def _GetBuildCommand(self
):
1659 if self
._BuildCommand
== None:
1660 self
._BuildCommand
= []
1661 if "MAKE" in self
.ToolDefinition
and "PATH" in self
.ToolDefinition
["MAKE"]:
1662 self
._BuildCommand
+= SplitOption(self
.ToolDefinition
["MAKE"]["PATH"])
1663 if "FLAGS" in self
.ToolDefinition
["MAKE"]:
1664 NewOption
= self
.ToolDefinition
["MAKE"]["FLAGS"].strip()
1666 self
._BuildCommand
+= SplitOption(NewOption
)
1667 return self
._BuildCommand
1669 ## Get tool chain definition
1671 # Get each tool defition for given tool chain from tools_def.txt and platform
1673 def _GetToolDefinition(self
):
1674 if self
._ToolDefinitions
== None:
1675 ToolDefinition
= self
.Workspace
.ToolDef
.ToolsDefTxtDictionary
1676 if TAB_TOD_DEFINES_COMMAND_TYPE
not in self
.Workspace
.ToolDef
.ToolsDefTxtDatabase
:
1677 EdkLogger
.error('build', RESOURCE_NOT_AVAILABLE
, "No tools found in configuration",
1678 ExtraData
="[%s]" % self
.MetaFile
)
1679 self
._ToolDefinitions
= {}
1681 for Def
in ToolDefinition
:
1682 Target
, Tag
, Arch
, Tool
, Attr
= Def
.split("_")
1683 if Target
!= self
.BuildTarget
or Tag
!= self
.ToolChain
or Arch
!= self
.Arch
:
1686 Value
= ToolDefinition
[Def
]
1687 # don't record the DLL
1689 DllPathList
.add(Value
)
1692 if Tool
not in self
._ToolDefinitions
:
1693 self
._ToolDefinitions
[Tool
] = {}
1694 self
._ToolDefinitions
[Tool
][Attr
] = Value
1698 if GlobalData
.gOptions
.SilentMode
and "MAKE" in self
._ToolDefinitions
:
1699 if "FLAGS" not in self
._ToolDefinitions
["MAKE"]:
1700 self
._ToolDefinitions
["MAKE"]["FLAGS"] = ""
1701 self
._ToolDefinitions
["MAKE"]["FLAGS"] += " -s"
1703 for Tool
in self
._ToolDefinitions
:
1704 for Attr
in self
._ToolDefinitions
[Tool
]:
1705 Value
= self
._ToolDefinitions
[Tool
][Attr
]
1706 if Tool
in self
.BuildOption
and Attr
in self
.BuildOption
[Tool
]:
1707 # check if override is indicated
1708 if self
.BuildOption
[Tool
][Attr
].startswith('='):
1709 Value
= self
.BuildOption
[Tool
][Attr
][1:]
1711 Value
+= " " + self
.BuildOption
[Tool
][Attr
]
1714 # Don't put MAKE definition in the file
1718 ToolsDef
+= "%s = %s\n" % (Tool
, Value
)
1720 # Don't put MAKE definition in the file
1725 ToolsDef
+= "%s_%s = %s\n" % (Tool
, Attr
, Value
)
1728 SaveFileOnChange(self
.ToolDefinitionFile
, ToolsDef
)
1729 for DllPath
in DllPathList
:
1730 os
.environ
["PATH"] = DllPath
+ os
.pathsep
+ os
.environ
["PATH"]
1731 os
.environ
["MAKE_FLAGS"] = MakeFlags
1733 return self
._ToolDefinitions
1735 ## Return the paths of tools
1736 def _GetToolDefFile(self
):
1737 if self
._ToolDefFile
== None:
1738 self
._ToolDefFile
= os
.path
.join(self
.MakeFileDir
, "TOOLS_DEF." + self
.Arch
)
1739 return self
._ToolDefFile
1741 ## Retrieve the toolchain family of given toolchain tag. Default to 'MSFT'.
1742 def _GetToolChainFamily(self
):
1743 if self
._ToolChainFamily
== None:
1744 ToolDefinition
= self
.Workspace
.ToolDef
.ToolsDefTxtDatabase
1745 if TAB_TOD_DEFINES_FAMILY
not in ToolDefinition \
1746 or self
.ToolChain
not in ToolDefinition
[TAB_TOD_DEFINES_FAMILY
] \
1747 or not ToolDefinition
[TAB_TOD_DEFINES_FAMILY
][self
.ToolChain
]:
1748 EdkLogger
.verbose("No tool chain family found in configuration for %s. Default to MSFT." \
1750 self
._ToolChainFamily
= "MSFT"
1752 self
._ToolChainFamily
= ToolDefinition
[TAB_TOD_DEFINES_FAMILY
][self
.ToolChain
]
1753 return self
._ToolChainFamily
1755 def _GetBuildRuleFamily(self
):
1756 if self
._BuildRuleFamily
== None:
1757 ToolDefinition
= self
.Workspace
.ToolDef
.ToolsDefTxtDatabase
1758 if TAB_TOD_DEFINES_BUILDRULEFAMILY
not in ToolDefinition \
1759 or self
.ToolChain
not in ToolDefinition
[TAB_TOD_DEFINES_BUILDRULEFAMILY
] \
1760 or not ToolDefinition
[TAB_TOD_DEFINES_BUILDRULEFAMILY
][self
.ToolChain
]:
1761 EdkLogger
.verbose("No tool chain family found in configuration for %s. Default to MSFT." \
1763 self
._BuildRuleFamily
= "MSFT"
1765 self
._BuildRuleFamily
= ToolDefinition
[TAB_TOD_DEFINES_BUILDRULEFAMILY
][self
.ToolChain
]
1766 return self
._BuildRuleFamily
1768 ## Return the build options specific for all modules in this platform
1769 def _GetBuildOptions(self
):
1770 if self
._BuildOption
== None:
1771 self
._BuildOption
= self
._ExpandBuildOption
(self
.Platform
.BuildOptions
)
1772 return self
._BuildOption
1774 ## Return the build options specific for EDK modules in this platform
1775 def _GetEdkBuildOptions(self
):
1776 if self
._EdkBuildOption
== None:
1777 self
._EdkBuildOption
= self
._ExpandBuildOption
(self
.Platform
.BuildOptions
, EDK_NAME
)
1778 return self
._EdkBuildOption
1780 ## Return the build options specific for EDKII modules in this platform
1781 def _GetEdkIIBuildOptions(self
):
1782 if self
._EdkIIBuildOption
== None:
1783 self
._EdkIIBuildOption
= self
._ExpandBuildOption
(self
.Platform
.BuildOptions
, EDKII_NAME
)
1784 return self
._EdkIIBuildOption
1786 ## Parse build_rule.txt in Conf Directory.
1788 # @retval BuildRule object
1790 def _GetBuildRule(self
):
1791 if self
._BuildRule
== None:
1792 BuildRuleFile
= None
1793 if TAB_TAT_DEFINES_BUILD_RULE_CONF
in self
.Workspace
.TargetTxt
.TargetTxtDictionary
:
1794 BuildRuleFile
= self
.Workspace
.TargetTxt
.TargetTxtDictionary
[TAB_TAT_DEFINES_BUILD_RULE_CONF
]
1795 if BuildRuleFile
in [None, '']:
1796 BuildRuleFile
= gDefaultBuildRuleFile
1797 self
._BuildRule
= BuildRule(BuildRuleFile
)
1798 if self
._BuildRule
._FileVersion
== "":
1799 self
._BuildRule
._FileVersion
= AutoGenReqBuildRuleVerNum
1801 if self
._BuildRule
._FileVersion
< AutoGenReqBuildRuleVerNum
:
1802 # If Build Rule's version is less than the version number required by the tools, halting the build.
1803 EdkLogger
.error("build", AUTOGEN_ERROR
,
1804 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])"\
1805 % (self
._BuildRule
._FileVersion
, AutoGenReqBuildRuleVerNum
))
1807 return self
._BuildRule
1809 ## Summarize the packages used by modules in this platform
1810 def _GetPackageList(self
):
1811 if self
._PackageList
== None:
1812 self
._PackageList
= set()
1813 for La
in self
.LibraryAutoGenList
:
1814 self
._PackageList
.update(La
.DependentPackageList
)
1815 for Ma
in self
.ModuleAutoGenList
:
1816 self
._PackageList
.update(Ma
.DependentPackageList
)
1817 #Collect package set information from INF of FDF
1819 for ModuleFile
in self
._AsBuildModuleList
:
1820 if ModuleFile
in self
.Platform
.Modules
:
1822 ModuleData
= self
.BuildDatabase
[ModuleFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1823 PkgSet
.update(ModuleData
.Packages
)
1824 self
._PackageList
= list(self
._PackageList
) + list (PkgSet
)
1825 return self
._PackageList
1827 def _GetNonDynamicPcdDict(self
):
1828 if self
._NonDynamicPcdDict
:
1829 return self
._NonDynamicPcdDict
1830 for Pcd
in self
.NonDynamicPcdList
:
1831 self
._NonDynamicPcdDict
[(Pcd
.TokenCName
,Pcd
.TokenSpaceGuidCName
)] = Pcd
1832 return self
._NonDynamicPcdDict
1834 ## Get list of non-dynamic PCDs
1835 def _GetNonDynamicPcdList(self
):
1836 if self
._NonDynamicPcdList
== None:
1837 self
.CollectPlatformDynamicPcds()
1838 return self
._NonDynamicPcdList
1840 ## Get list of dynamic PCDs
1841 def _GetDynamicPcdList(self
):
1842 if self
._DynamicPcdList
== None:
1843 self
.CollectPlatformDynamicPcds()
1844 return self
._DynamicPcdList
1846 ## Generate Token Number for all PCD
1847 def _GetPcdTokenNumbers(self
):
1848 if self
._PcdTokenNumber
== None:
1849 self
._PcdTokenNumber
= sdict()
1852 # Make the Dynamic and DynamicEx PCD use within different TokenNumber area.
1856 # TokenNumber 0 ~ 10
1858 # TokeNumber 11 ~ 20
1860 for Pcd
in self
.DynamicPcdList
:
1861 if Pcd
.Phase
== "PEI":
1862 if Pcd
.Type
in ["Dynamic", "DynamicDefault", "DynamicVpd", "DynamicHii"]:
1863 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
1864 self
._PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
1867 for Pcd
in self
.DynamicPcdList
:
1868 if Pcd
.Phase
== "PEI":
1869 if Pcd
.Type
in ["DynamicEx", "DynamicExDefault", "DynamicExVpd", "DynamicExHii"]:
1870 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
1871 self
._PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
1874 for Pcd
in self
.DynamicPcdList
:
1875 if Pcd
.Phase
== "DXE":
1876 if Pcd
.Type
in ["Dynamic", "DynamicDefault", "DynamicVpd", "DynamicHii"]:
1877 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
1878 self
._PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
1881 for Pcd
in self
.DynamicPcdList
:
1882 if Pcd
.Phase
== "DXE":
1883 if Pcd
.Type
in ["DynamicEx", "DynamicExDefault", "DynamicExVpd", "DynamicExHii"]:
1884 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
1885 self
._PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
1888 for Pcd
in self
.NonDynamicPcdList
:
1889 self
._PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
1891 return self
._PcdTokenNumber
1893 ## Summarize ModuleAutoGen objects of all modules/libraries to be built for this platform
1894 def _GetAutoGenObjectList(self
):
1895 self
._ModuleAutoGenList
= []
1896 self
._LibraryAutoGenList
= []
1897 for ModuleFile
in self
.Platform
.Modules
:
1906 if Ma
not in self
._ModuleAutoGenList
:
1907 self
._ModuleAutoGenList
.append(Ma
)
1908 for La
in Ma
.LibraryAutoGenList
:
1909 if La
not in self
._LibraryAutoGenList
:
1910 self
._LibraryAutoGenList
.append(La
)
1911 if Ma
not in La
._ReferenceModules
:
1912 La
._ReferenceModules
.append(Ma
)
1914 ## Summarize ModuleAutoGen objects of all modules to be built for this platform
1915 def _GetModuleAutoGenList(self
):
1916 if self
._ModuleAutoGenList
== None:
1917 self
._GetAutoGenObjectList
()
1918 return self
._ModuleAutoGenList
1920 ## Summarize ModuleAutoGen objects of all libraries to be built for this platform
1921 def _GetLibraryAutoGenList(self
):
1922 if self
._LibraryAutoGenList
== None:
1923 self
._GetAutoGenObjectList
()
1924 return self
._LibraryAutoGenList
1926 ## Test if a module is supported by the platform
1928 # An error will be raised directly if the module or its arch is not supported
1929 # by the platform or current configuration
1931 def ValidModule(self
, Module
):
1932 return Module
in self
.Platform
.Modules
or Module
in self
.Platform
.LibraryInstances \
1933 or Module
in self
._AsBuildModuleList
1935 ## Resolve the library classes in a module to library instances
1937 # This method will not only resolve library classes but also sort the library
1938 # instances according to the dependency-ship.
1940 # @param Module The module from which the library classes will be resolved
1942 # @retval library_list List of library instances sorted
1944 def ApplyLibraryInstance(self
, Module
):
1945 # Cover the case that the binary INF file is list in the FDF file but not DSC file, return empty list directly
1946 if str(Module
) not in self
.Platform
.Modules
:
1949 ModuleType
= Module
.ModuleType
1951 # for overridding library instances with module specific setting
1952 PlatformModule
= self
.Platform
.Modules
[str(Module
)]
1954 # add forced library instances (specified under LibraryClasses sections)
1956 # If a module has a MODULE_TYPE of USER_DEFINED,
1957 # do not link in NULL library class instances from the global [LibraryClasses.*] sections.
1959 if Module
.ModuleType
!= SUP_MODULE_USER_DEFINED
:
1960 for LibraryClass
in self
.Platform
.LibraryClasses
.GetKeys():
1961 if LibraryClass
.startswith("NULL") and self
.Platform
.LibraryClasses
[LibraryClass
, Module
.ModuleType
]:
1962 Module
.LibraryClasses
[LibraryClass
] = self
.Platform
.LibraryClasses
[LibraryClass
, Module
.ModuleType
]
1964 # add forced library instances (specified in module overrides)
1965 for LibraryClass
in PlatformModule
.LibraryClasses
:
1966 if LibraryClass
.startswith("NULL"):
1967 Module
.LibraryClasses
[LibraryClass
] = PlatformModule
.LibraryClasses
[LibraryClass
]
1970 LibraryConsumerList
= [Module
]
1972 ConsumedByList
= sdict()
1973 LibraryInstance
= sdict()
1975 EdkLogger
.verbose("")
1976 EdkLogger
.verbose("Library instances of module [%s] [%s]:" % (str(Module
), self
.Arch
))
1977 while len(LibraryConsumerList
) > 0:
1978 M
= LibraryConsumerList
.pop()
1979 for LibraryClassName
in M
.LibraryClasses
:
1980 if LibraryClassName
not in LibraryInstance
:
1981 # override library instance for this module
1982 if LibraryClassName
in PlatformModule
.LibraryClasses
:
1983 LibraryPath
= PlatformModule
.LibraryClasses
[LibraryClassName
]
1985 LibraryPath
= self
.Platform
.LibraryClasses
[LibraryClassName
, ModuleType
]
1986 if LibraryPath
== None or LibraryPath
== "":
1987 LibraryPath
= M
.LibraryClasses
[LibraryClassName
]
1988 if LibraryPath
== None or LibraryPath
== "":
1989 EdkLogger
.error("build", RESOURCE_NOT_AVAILABLE
,
1990 "Instance of library class [%s] is not found" % LibraryClassName
,
1992 ExtraData
="in [%s] [%s]\n\tconsumed by module [%s]" % (str(M
), self
.Arch
, str(Module
)))
1994 LibraryModule
= self
.BuildDatabase
[LibraryPath
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1995 # for those forced library instance (NULL library), add a fake library class
1996 if LibraryClassName
.startswith("NULL"):
1997 LibraryModule
.LibraryClass
.append(LibraryClassObject(LibraryClassName
, [ModuleType
]))
1998 elif LibraryModule
.LibraryClass
== None \
1999 or len(LibraryModule
.LibraryClass
) == 0 \
2000 or (ModuleType
!= 'USER_DEFINED'
2001 and ModuleType
not in LibraryModule
.LibraryClass
[0].SupModList
):
2002 # only USER_DEFINED can link against any library instance despite of its SupModList
2003 EdkLogger
.error("build", OPTION_MISSING
,
2004 "Module type [%s] is not supported by library instance [%s]" \
2005 % (ModuleType
, LibraryPath
), File
=self
.MetaFile
,
2006 ExtraData
="consumed by [%s]" % str(Module
))
2008 LibraryInstance
[LibraryClassName
] = LibraryModule
2009 LibraryConsumerList
.append(LibraryModule
)
2010 EdkLogger
.verbose("\t" + str(LibraryClassName
) + " : " + str(LibraryModule
))
2012 LibraryModule
= LibraryInstance
[LibraryClassName
]
2014 if LibraryModule
== None:
2017 if LibraryModule
.ConstructorList
!= [] and LibraryModule
not in Constructor
:
2018 Constructor
.append(LibraryModule
)
2020 if LibraryModule
not in ConsumedByList
:
2021 ConsumedByList
[LibraryModule
] = []
2022 # don't add current module itself to consumer list
2024 if M
in ConsumedByList
[LibraryModule
]:
2026 ConsumedByList
[LibraryModule
].append(M
)
2028 # Initialize the sorted output list to the empty set
2030 SortedLibraryList
= []
2032 # Q <- Set of all nodes with no incoming edges
2034 LibraryList
= [] #LibraryInstance.values()
2036 for LibraryClassName
in LibraryInstance
:
2037 M
= LibraryInstance
[LibraryClassName
]
2038 LibraryList
.append(M
)
2039 if ConsumedByList
[M
] == []:
2043 # start the DAG algorithm
2047 while Q
== [] and EdgeRemoved
:
2049 # for each node Item with a Constructor
2050 for Item
in LibraryList
:
2051 if Item
not in Constructor
:
2053 # for each Node without a constructor with an edge e from Item to Node
2054 for Node
in ConsumedByList
[Item
]:
2055 if Node
in Constructor
:
2057 # remove edge e from the graph if Node has no constructor
2058 ConsumedByList
[Item
].remove(Node
)
2060 if ConsumedByList
[Item
] == []:
2061 # insert Item into Q
2066 # DAG is done if there's no more incoming edge for all nodes
2070 # remove node from Q
2073 SortedLibraryList
.append(Node
)
2075 # for each node Item with an edge e from Node to Item do
2076 for Item
in LibraryList
:
2077 if Node
not in ConsumedByList
[Item
]:
2079 # remove edge e from the graph
2080 ConsumedByList
[Item
].remove(Node
)
2082 if ConsumedByList
[Item
] != []:
2084 # insert Item into Q, if Item has no other incoming edges
2088 # if any remaining node Item in the graph has a constructor and an incoming edge, then the graph has a cycle
2090 for Item
in LibraryList
:
2091 if ConsumedByList
[Item
] != [] and Item
in Constructor
and len(Constructor
) > 1:
2092 ErrorMessage
= "\tconsumed by " + "\n\tconsumed by ".join([str(L
) for L
in ConsumedByList
[Item
]])
2093 EdkLogger
.error("build", BUILD_ERROR
, 'Library [%s] with constructors has a cycle' % str(Item
),
2094 ExtraData
=ErrorMessage
, File
=self
.MetaFile
)
2095 if Item
not in SortedLibraryList
:
2096 SortedLibraryList
.append(Item
)
2099 # Build the list of constructor and destructir names
2100 # The DAG Topo sort produces the destructor order, so the list of constructors must generated in the reverse order
2102 SortedLibraryList
.reverse()
2103 return SortedLibraryList
2106 ## Override PCD setting (type, value, ...)
2108 # @param ToPcd The PCD to be overrided
2109 # @param FromPcd The PCD overrideing from
2111 def _OverridePcd(self
, ToPcd
, FromPcd
, Module
=""):
2113 # in case there's PCDs coming from FDF file, which have no type given.
2114 # at this point, ToPcd.Type has the type found from dependent
2117 TokenCName
= ToPcd
.TokenCName
2118 for PcdItem
in GlobalData
.MixedPcd
:
2119 if (ToPcd
.TokenCName
, ToPcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
2120 TokenCName
= PcdItem
[0]
2123 if GlobalData
.BuildOptionPcd
:
2124 for pcd
in GlobalData
.BuildOptionPcd
:
2125 if (FromPcd
.TokenSpaceGuidCName
, FromPcd
.TokenCName
) == (pcd
[0], pcd
[1]):
2126 FromPcd
.DefaultValue
= pcd
[2]
2128 if ToPcd
.Pending
and FromPcd
.Type
not in [None, '']:
2129 ToPcd
.Type
= FromPcd
.Type
2130 elif (ToPcd
.Type
not in [None, '']) and (FromPcd
.Type
not in [None, ''])\
2131 and (ToPcd
.Type
!= FromPcd
.Type
) and (ToPcd
.Type
in FromPcd
.Type
):
2132 if ToPcd
.Type
.strip() == "DynamicEx":
2133 ToPcd
.Type
= FromPcd
.Type
2134 elif ToPcd
.Type
not in [None, ''] and FromPcd
.Type
not in [None, ''] \
2135 and ToPcd
.Type
!= FromPcd
.Type
:
2136 EdkLogger
.error("build", OPTION_CONFLICT
, "Mismatched PCD type",
2137 ExtraData
="%s.%s is defined as [%s] in module %s, but as [%s] in platform."\
2138 % (ToPcd
.TokenSpaceGuidCName
, TokenCName
,
2139 ToPcd
.Type
, Module
, FromPcd
.Type
),
2142 if FromPcd
.MaxDatumSize
not in [None, '']:
2143 ToPcd
.MaxDatumSize
= FromPcd
.MaxDatumSize
2144 if FromPcd
.DefaultValue
not in [None, '']:
2145 ToPcd
.DefaultValue
= FromPcd
.DefaultValue
2146 if FromPcd
.TokenValue
not in [None, '']:
2147 ToPcd
.TokenValue
= FromPcd
.TokenValue
2148 if FromPcd
.MaxDatumSize
not in [None, '']:
2149 ToPcd
.MaxDatumSize
= FromPcd
.MaxDatumSize
2150 if FromPcd
.DatumType
not in [None, '']:
2151 ToPcd
.DatumType
= FromPcd
.DatumType
2152 if FromPcd
.SkuInfoList
not in [None, '', []]:
2153 ToPcd
.SkuInfoList
= FromPcd
.SkuInfoList
2155 # check the validation of datum
2156 IsValid
, Cause
= CheckPcdDatum(ToPcd
.DatumType
, ToPcd
.DefaultValue
)
2158 EdkLogger
.error('build', FORMAT_INVALID
, Cause
, File
=self
.MetaFile
,
2159 ExtraData
="%s.%s" % (ToPcd
.TokenSpaceGuidCName
, TokenCName
))
2160 ToPcd
.validateranges
= FromPcd
.validateranges
2161 ToPcd
.validlists
= FromPcd
.validlists
2162 ToPcd
.expressions
= FromPcd
.expressions
2164 if ToPcd
.DatumType
== "VOID*" and ToPcd
.MaxDatumSize
in ['', None]:
2165 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "No MaxDatumSize specified for PCD %s.%s" \
2166 % (ToPcd
.TokenSpaceGuidCName
, TokenCName
))
2167 Value
= ToPcd
.DefaultValue
2168 if Value
in [None, '']:
2169 ToPcd
.MaxDatumSize
= '1'
2170 elif Value
[0] == 'L':
2171 ToPcd
.MaxDatumSize
= str((len(Value
) - 2) * 2)
2172 elif Value
[0] == '{':
2173 ToPcd
.MaxDatumSize
= str(len(Value
.split(',')))
2175 ToPcd
.MaxDatumSize
= str(len(Value
) - 1)
2177 # apply default SKU for dynamic PCDS if specified one is not available
2178 if (ToPcd
.Type
in PCD_DYNAMIC_TYPE_LIST
or ToPcd
.Type
in PCD_DYNAMIC_EX_TYPE_LIST
) \
2179 and ToPcd
.SkuInfoList
in [None, {}, '']:
2180 if self
.Platform
.SkuName
in self
.Platform
.SkuIds
:
2181 SkuName
= self
.Platform
.SkuName
2184 ToPcd
.SkuInfoList
= {
2185 SkuName
: SkuInfoClass(SkuName
, self
.Platform
.SkuIds
[SkuName
], '', '', '', '', '', ToPcd
.DefaultValue
)
2188 ## Apply PCD setting defined platform to a module
2190 # @param Module The module from which the PCD setting will be overrided
2192 # @retval PCD_list The list PCDs with settings from platform
2194 def ApplyPcdSetting(self
, Module
, Pcds
):
2195 # for each PCD in module
2196 for Name
, Guid
in Pcds
:
2197 PcdInModule
= Pcds
[Name
, Guid
]
2198 # find out the PCD setting in platform
2199 if (Name
, Guid
) in self
.Platform
.Pcds
:
2200 PcdInPlatform
= self
.Platform
.Pcds
[Name
, Guid
]
2202 PcdInPlatform
= None
2203 # then override the settings if any
2204 self
._OverridePcd
(PcdInModule
, PcdInPlatform
, Module
)
2205 # resolve the VariableGuid value
2206 for SkuId
in PcdInModule
.SkuInfoList
:
2207 Sku
= PcdInModule
.SkuInfoList
[SkuId
]
2208 if Sku
.VariableGuid
== '': continue
2209 Sku
.VariableGuidValue
= GuidValue(Sku
.VariableGuid
, self
.PackageList
, self
.MetaFile
.Path
)
2210 if Sku
.VariableGuidValue
== None:
2211 PackageList
= "\n\t".join([str(P
) for P
in self
.PackageList
])
2214 RESOURCE_NOT_AVAILABLE
,
2215 "Value of GUID [%s] is not found in" % Sku
.VariableGuid
,
2216 ExtraData
=PackageList
+ "\n\t(used with %s.%s from module %s)" \
2217 % (Guid
, Name
, str(Module
)),
2221 # override PCD settings with module specific setting
2222 if Module
in self
.Platform
.Modules
:
2223 PlatformModule
= self
.Platform
.Modules
[str(Module
)]
2224 for Key
in PlatformModule
.Pcds
:
2226 self
._OverridePcd
(Pcds
[Key
], PlatformModule
.Pcds
[Key
], Module
)
2227 return Pcds
.values()
2229 ## Resolve library names to library modules
2231 # (for Edk.x modules)
2233 # @param Module The module from which the library names will be resolved
2235 # @retval library_list The list of library modules
2237 def ResolveLibraryReference(self
, Module
):
2238 EdkLogger
.verbose("")
2239 EdkLogger
.verbose("Library instances of module [%s] [%s]:" % (str(Module
), self
.Arch
))
2240 LibraryConsumerList
= [Module
]
2242 # "CompilerStub" is a must for Edk modules
2243 if Module
.Libraries
:
2244 Module
.Libraries
.append("CompilerStub")
2246 while len(LibraryConsumerList
) > 0:
2247 M
= LibraryConsumerList
.pop()
2248 for LibraryName
in M
.Libraries
:
2249 Library
= self
.Platform
.LibraryClasses
[LibraryName
, ':dummy:']
2251 for Key
in self
.Platform
.LibraryClasses
.data
.keys():
2252 if LibraryName
.upper() == Key
.upper():
2253 Library
= self
.Platform
.LibraryClasses
[Key
, ':dummy:']
2256 EdkLogger
.warn("build", "Library [%s] is not found" % LibraryName
, File
=str(M
),
2257 ExtraData
="\t%s [%s]" % (str(Module
), self
.Arch
))
2260 if Library
not in LibraryList
:
2261 LibraryList
.append(Library
)
2262 LibraryConsumerList
.append(Library
)
2263 EdkLogger
.verbose("\t" + LibraryName
+ " : " + str(Library
) + ' ' + str(type(Library
)))
2266 ## Calculate the priority value of the build option
2268 # @param Key Build option definition contain: TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
2270 # @retval Value Priority value based on the priority list.
2272 def CalculatePriorityValue(self
, Key
):
2273 Target
, ToolChain
, Arch
, CommandType
, Attr
= Key
.split('_')
2274 PriorityValue
= 0x11111
2276 PriorityValue
&= 0x01111
2277 if ToolChain
== "*":
2278 PriorityValue
&= 0x10111
2280 PriorityValue
&= 0x11011
2281 if CommandType
== "*":
2282 PriorityValue
&= 0x11101
2284 PriorityValue
&= 0x11110
2286 return self
.PrioList
["0x%0.5x" % PriorityValue
]
2289 ## Expand * in build option key
2291 # @param Options Options to be expanded
2293 # @retval options Options expanded
2295 def _ExpandBuildOption(self
, Options
, ModuleStyle
=None):
2302 # Construct a list contain the build options which need override.
2306 # Key[0] -- tool family
2307 # Key[1] -- TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
2309 if (Key
[0] == self
.BuildRuleFamily
and
2310 (ModuleStyle
== None or len(Key
) < 3 or (len(Key
) > 2 and Key
[2] == ModuleStyle
))):
2311 Target
, ToolChain
, Arch
, CommandType
, Attr
= Key
[1].split('_')
2312 if Target
== self
.BuildTarget
or Target
== "*":
2313 if ToolChain
== self
.ToolChain
or ToolChain
== "*":
2314 if Arch
== self
.Arch
or Arch
== "*":
2315 if Options
[Key
].startswith("="):
2316 if OverrideList
.get(Key
[1]) != None:
2317 OverrideList
.pop(Key
[1])
2318 OverrideList
[Key
[1]] = Options
[Key
]
2321 # Use the highest priority value.
2323 if (len(OverrideList
) >= 2):
2324 KeyList
= OverrideList
.keys()
2325 for Index
in range(len(KeyList
)):
2326 NowKey
= KeyList
[Index
]
2327 Target1
, ToolChain1
, Arch1
, CommandType1
, Attr1
= NowKey
.split("_")
2328 for Index1
in range(len(KeyList
) - Index
- 1):
2329 NextKey
= KeyList
[Index1
+ Index
+ 1]
2331 # Compare two Key, if one is included by another, choose the higher priority one
2333 Target2
, ToolChain2
, Arch2
, CommandType2
, Attr2
= NextKey
.split("_")
2334 if Target1
== Target2
or Target1
== "*" or Target2
== "*":
2335 if ToolChain1
== ToolChain2
or ToolChain1
== "*" or ToolChain2
== "*":
2336 if Arch1
== Arch2
or Arch1
== "*" or Arch2
== "*":
2337 if CommandType1
== CommandType2
or CommandType1
== "*" or CommandType2
== "*":
2338 if Attr1
== Attr2
or Attr1
== "*" or Attr2
== "*":
2339 if self
.CalculatePriorityValue(NowKey
) > self
.CalculatePriorityValue(NextKey
):
2340 if Options
.get((self
.BuildRuleFamily
, NextKey
)) != None:
2341 Options
.pop((self
.BuildRuleFamily
, NextKey
))
2343 if Options
.get((self
.BuildRuleFamily
, NowKey
)) != None:
2344 Options
.pop((self
.BuildRuleFamily
, NowKey
))
2347 if ModuleStyle
!= None and len (Key
) > 2:
2348 # Check Module style is EDK or EDKII.
2349 # Only append build option for the matched style module.
2350 if ModuleStyle
== EDK_NAME
and Key
[2] != EDK_NAME
:
2352 elif ModuleStyle
== EDKII_NAME
and Key
[2] != EDKII_NAME
:
2355 Target
, Tag
, Arch
, Tool
, Attr
= Key
[1].split("_")
2356 # if tool chain family doesn't match, skip it
2357 if Tool
in self
.ToolDefinition
and Family
!= "":
2358 FamilyIsNull
= False
2359 if self
.ToolDefinition
[Tool
].get(TAB_TOD_DEFINES_BUILDRULEFAMILY
, "") != "":
2360 if Family
!= self
.ToolDefinition
[Tool
][TAB_TOD_DEFINES_BUILDRULEFAMILY
]:
2362 elif Family
!= self
.ToolDefinition
[Tool
][TAB_TOD_DEFINES_FAMILY
]:
2365 # expand any wildcard
2366 if Target
== "*" or Target
== self
.BuildTarget
:
2367 if Tag
== "*" or Tag
== self
.ToolChain
:
2368 if Arch
== "*" or Arch
== self
.Arch
:
2369 if Tool
not in BuildOptions
:
2370 BuildOptions
[Tool
] = {}
2371 if Attr
!= "FLAGS" or Attr
not in BuildOptions
[Tool
] or Options
[Key
].startswith('='):
2372 BuildOptions
[Tool
][Attr
] = Options
[Key
]
2374 # append options for the same tool
2375 BuildOptions
[Tool
][Attr
] += " " + Options
[Key
]
2376 # Build Option Family has been checked, which need't to be checked again for family.
2377 if FamilyMatch
or FamilyIsNull
:
2381 if ModuleStyle
!= None and len (Key
) > 2:
2382 # Check Module style is EDK or EDKII.
2383 # Only append build option for the matched style module.
2384 if ModuleStyle
== EDK_NAME
and Key
[2] != EDK_NAME
:
2386 elif ModuleStyle
== EDKII_NAME
and Key
[2] != EDKII_NAME
:
2389 Target
, Tag
, Arch
, Tool
, Attr
= Key
[1].split("_")
2390 # if tool chain family doesn't match, skip it
2391 if Tool
not in self
.ToolDefinition
or Family
== "":
2393 # option has been added before
2394 if Family
!= self
.ToolDefinition
[Tool
][TAB_TOD_DEFINES_FAMILY
]:
2397 # expand any wildcard
2398 if Target
== "*" or Target
== self
.BuildTarget
:
2399 if Tag
== "*" or Tag
== self
.ToolChain
:
2400 if Arch
== "*" or Arch
== self
.Arch
:
2401 if Tool
not in BuildOptions
:
2402 BuildOptions
[Tool
] = {}
2403 if Attr
!= "FLAGS" or Attr
not in BuildOptions
[Tool
] or Options
[Key
].startswith('='):
2404 BuildOptions
[Tool
][Attr
] = Options
[Key
]
2406 # append options for the same tool
2407 BuildOptions
[Tool
][Attr
] += " " + Options
[Key
]
2410 ## Append build options in platform to a module
2412 # @param Module The module to which the build options will be appened
2414 # @retval options The options appended with build options in platform
2416 def ApplyBuildOption(self
, Module
):
2417 # Get the different options for the different style module
2418 if Module
.AutoGenVersion
< 0x00010005:
2419 PlatformOptions
= self
.EdkBuildOption
2420 ModuleTypeOptions
= self
.Platform
.GetBuildOptionsByModuleType(EDK_NAME
, Module
.ModuleType
)
2422 PlatformOptions
= self
.EdkIIBuildOption
2423 ModuleTypeOptions
= self
.Platform
.GetBuildOptionsByModuleType(EDKII_NAME
, Module
.ModuleType
)
2424 ModuleTypeOptions
= self
._ExpandBuildOption
(ModuleTypeOptions
)
2425 ModuleOptions
= self
._ExpandBuildOption
(Module
.BuildOptions
)
2426 if Module
in self
.Platform
.Modules
:
2427 PlatformModule
= self
.Platform
.Modules
[str(Module
)]
2428 PlatformModuleOptions
= self
._ExpandBuildOption
(PlatformModule
.BuildOptions
)
2430 PlatformModuleOptions
= {}
2432 BuildRuleOrder
= None
2433 for Options
in [self
.ToolDefinition
, ModuleOptions
, PlatformOptions
, ModuleTypeOptions
, PlatformModuleOptions
]:
2434 for Tool
in Options
:
2435 for Attr
in Options
[Tool
]:
2436 if Attr
== TAB_TOD_DEFINES_BUILDRULEORDER
:
2437 BuildRuleOrder
= Options
[Tool
][Attr
]
2439 AllTools
= set(ModuleOptions
.keys() + PlatformOptions
.keys() +
2440 PlatformModuleOptions
.keys() + ModuleTypeOptions
.keys() +
2441 self
.ToolDefinition
.keys())
2443 for Tool
in AllTools
:
2444 if Tool
not in BuildOptions
:
2445 BuildOptions
[Tool
] = {}
2447 for Options
in [self
.ToolDefinition
, ModuleOptions
, PlatformOptions
, ModuleTypeOptions
, PlatformModuleOptions
]:
2448 if Tool
not in Options
:
2450 for Attr
in Options
[Tool
]:
2451 Value
= Options
[Tool
][Attr
]
2453 # Do not generate it in Makefile
2455 if Attr
== TAB_TOD_DEFINES_BUILDRULEORDER
:
2457 if Attr
not in BuildOptions
[Tool
]:
2458 BuildOptions
[Tool
][Attr
] = ""
2459 # check if override is indicated
2460 if Value
.startswith('='):
2461 ToolPath
= Value
[1:]
2462 ToolPath
= mws
.handleWsMacro(ToolPath
)
2463 BuildOptions
[Tool
][Attr
] = ToolPath
2465 Value
= mws
.handleWsMacro(Value
)
2466 BuildOptions
[Tool
][Attr
] += " " + Value
2467 if Module
.AutoGenVersion
< 0x00010005 and self
.Workspace
.UniFlag
!= None:
2469 # Override UNI flag only for EDK module.
2471 if 'BUILD' not in BuildOptions
:
2472 BuildOptions
['BUILD'] = {}
2473 BuildOptions
['BUILD']['FLAGS'] = self
.Workspace
.UniFlag
2474 return BuildOptions
, BuildRuleOrder
2476 Platform
= property(_GetPlatform
)
2477 Name
= property(_GetName
)
2478 Guid
= property(_GetGuid
)
2479 Version
= property(_GetVersion
)
2481 OutputDir
= property(_GetOutputDir
)
2482 BuildDir
= property(_GetBuildDir
)
2483 MakeFileDir
= property(_GetMakeFileDir
)
2484 FdfFile
= property(_GetFdfFile
)
2486 PcdTokenNumber
= property(_GetPcdTokenNumbers
) # (TokenCName, TokenSpaceGuidCName) : GeneratedTokenNumber
2487 DynamicPcdList
= property(_GetDynamicPcdList
) # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
2488 NonDynamicPcdList
= property(_GetNonDynamicPcdList
) # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
2489 NonDynamicPcdDict
= property(_GetNonDynamicPcdDict
)
2490 PackageList
= property(_GetPackageList
)
2492 ToolDefinition
= property(_GetToolDefinition
) # toolcode : tool path
2493 ToolDefinitionFile
= property(_GetToolDefFile
) # toolcode : lib path
2494 ToolChainFamily
= property(_GetToolChainFamily
)
2495 BuildRuleFamily
= property(_GetBuildRuleFamily
)
2496 BuildOption
= property(_GetBuildOptions
) # toolcode : option
2497 EdkBuildOption
= property(_GetEdkBuildOptions
) # edktoolcode : option
2498 EdkIIBuildOption
= property(_GetEdkIIBuildOptions
) # edkiitoolcode : option
2500 BuildCommand
= property(_GetBuildCommand
)
2501 BuildRule
= property(_GetBuildRule
)
2502 ModuleAutoGenList
= property(_GetModuleAutoGenList
)
2503 LibraryAutoGenList
= property(_GetLibraryAutoGenList
)
2504 GenFdsCommand
= property(_GenFdsCommand
)
2506 ## ModuleAutoGen class
2508 # This class encapsules the AutoGen behaviors for the build tools. In addition to
2509 # the generation of AutoGen.h and AutoGen.c, it will generate *.depex file according
2510 # to the [depex] section in module's inf file.
2512 class ModuleAutoGen(AutoGen
):
2513 ## The real constructor of ModuleAutoGen
2515 # This method is not supposed to be called by users of ModuleAutoGen. It's
2516 # only used by factory method __new__() to do real initialization work for an
2517 # object of ModuleAutoGen
2519 # @param Workspace EdkIIWorkspaceBuild object
2520 # @param ModuleFile The path of module file
2521 # @param Target Build target (DEBUG, RELEASE)
2522 # @param Toolchain Name of tool chain
2523 # @param Arch The arch the module supports
2524 # @param PlatformFile Platform meta-file
2526 def _Init(self
, Workspace
, ModuleFile
, Target
, Toolchain
, Arch
, PlatformFile
):
2527 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "AutoGen module [%s] [%s]" % (ModuleFile
, Arch
))
2528 GlobalData
.gProcessingFile
= "%s [%s, %s, %s]" % (ModuleFile
, Arch
, Toolchain
, Target
)
2530 self
.Workspace
= Workspace
2531 self
.WorkspaceDir
= Workspace
.WorkspaceDir
2533 self
.MetaFile
= ModuleFile
2534 self
.PlatformInfo
= PlatformAutoGen(Workspace
, PlatformFile
, Target
, Toolchain
, Arch
)
2535 # check if this module is employed by active platform
2536 if not self
.PlatformInfo
.ValidModule(self
.MetaFile
):
2537 EdkLogger
.verbose("Module [%s] for [%s] is not employed by active platform\n" \
2538 % (self
.MetaFile
, Arch
))
2541 self
.SourceDir
= self
.MetaFile
.SubDir
2542 self
.SourceDir
= mws
.relpath(self
.SourceDir
, self
.WorkspaceDir
)
2544 self
.SourceOverrideDir
= None
2545 # use overrided path defined in DSC file
2546 if self
.MetaFile
.Key
in GlobalData
.gOverrideDir
:
2547 self
.SourceOverrideDir
= GlobalData
.gOverrideDir
[self
.MetaFile
.Key
]
2549 self
.ToolChain
= Toolchain
2550 self
.BuildTarget
= Target
2552 self
.ToolChainFamily
= self
.PlatformInfo
.ToolChainFamily
2553 self
.BuildRuleFamily
= self
.PlatformInfo
.BuildRuleFamily
2555 self
.IsMakeFileCreated
= False
2556 self
.IsCodeFileCreated
= False
2557 self
.IsAsBuiltInfCreated
= False
2558 self
.DepexGenerated
= False
2560 self
.BuildDatabase
= self
.Workspace
.BuildDatabase
2561 self
.BuildRuleOrder
= None
2566 self
._Version
= None
2567 self
._ModuleType
= None
2568 self
._ComponentType
= None
2569 self
._PcdIsDriver
= None
2570 self
._AutoGenVersion
= None
2571 self
._LibraryFlag
= None
2572 self
._CustomMakefile
= None
2575 self
._BuildDir
= None
2576 self
._OutputDir
= None
2577 self
._DebugDir
= None
2578 self
._MakeFileDir
= None
2580 self
._IncludePathList
= None
2581 self
._IncludePathLength
= 0
2582 self
._AutoGenFileList
= None
2583 self
._UnicodeFileList
= None
2584 self
._SourceFileList
= None
2585 self
._ObjectFileList
= None
2586 self
._BinaryFileList
= None
2588 self
._DependentPackageList
= None
2589 self
._DependentLibraryList
= None
2590 self
._LibraryAutoGenList
= None
2591 self
._DerivedPackageList
= None
2592 self
._ModulePcdList
= None
2593 self
._LibraryPcdList
= None
2594 self
._PcdComments
= sdict()
2595 self
._GuidList
= None
2596 self
._GuidsUsedByPcd
= None
2597 self
._GuidComments
= sdict()
2598 self
._ProtocolList
= None
2599 self
._ProtocolComments
= sdict()
2600 self
._PpiList
= None
2601 self
._PpiComments
= sdict()
2602 self
._DepexList
= None
2603 self
._DepexExpressionList
= None
2604 self
._BuildOption
= None
2605 self
._BuildOptionIncPathList
= None
2606 self
._BuildTargets
= None
2607 self
._IntroBuildTargetList
= None
2608 self
._FinalBuildTargetList
= None
2609 self
._FileTypes
= None
2610 self
._BuildRules
= None
2612 ## The Modules referenced to this Library
2613 # Only Library has this attribute
2614 self
._ReferenceModules
= []
2616 ## Store the FixedAtBuild Pcds
2618 self
._FixedAtBuildPcds
= []
2623 return "%s [%s]" % (self
.MetaFile
, self
.Arch
)
2625 # Get FixedAtBuild Pcds of this Module
2626 def _GetFixedAtBuildPcds(self
):
2627 if self
._FixedAtBuildPcds
:
2628 return self
._FixedAtBuildPcds
2629 for Pcd
in self
.ModulePcdList
:
2631 if not (Pcd
.Pending
== False and Pcd
.Type
== "FixedAtBuild"):
2633 elif Pcd
.Type
!= "FixedAtBuild":
2635 if Pcd
not in self
._FixedAtBuildPcds
:
2636 self
._FixedAtBuildPcds
.append(Pcd
)
2638 return self
._FixedAtBuildPcds
2640 def _GetUniqueBaseName(self
):
2641 BaseName
= self
.Name
2642 for Module
in self
.PlatformInfo
.ModuleAutoGenList
:
2643 if Module
.MetaFile
== self
.MetaFile
:
2645 if Module
.Name
== self
.Name
:
2646 if uuid
.UUID(Module
.Guid
) == uuid
.UUID(self
.Guid
):
2647 EdkLogger
.error("build", FILE_DUPLICATED
, 'Modules have same BaseName and FILE_GUID:\n'
2648 ' %s\n %s' % (Module
.MetaFile
, self
.MetaFile
))
2649 BaseName
= '%s_%s' % (self
.Name
, self
.Guid
)
2652 # Macros could be used in build_rule.txt (also Makefile)
2653 def _GetMacros(self
):
2654 if self
._Macro
== None:
2655 self
._Macro
= sdict()
2656 self
._Macro
["WORKSPACE" ] = self
.WorkspaceDir
2657 self
._Macro
["MODULE_NAME" ] = self
.Name
2658 self
._Macro
["MODULE_NAME_GUID" ] = self
._GetUniqueBaseName
()
2659 self
._Macro
["MODULE_GUID" ] = self
.Guid
2660 self
._Macro
["MODULE_VERSION" ] = self
.Version
2661 self
._Macro
["MODULE_TYPE" ] = self
.ModuleType
2662 self
._Macro
["MODULE_FILE" ] = str(self
.MetaFile
)
2663 self
._Macro
["MODULE_FILE_BASE_NAME" ] = self
.MetaFile
.BaseName
2664 self
._Macro
["MODULE_RELATIVE_DIR" ] = self
.SourceDir
2665 self
._Macro
["MODULE_DIR" ] = self
.SourceDir
2667 self
._Macro
["BASE_NAME" ] = self
.Name
2669 self
._Macro
["ARCH" ] = self
.Arch
2670 self
._Macro
["TOOLCHAIN" ] = self
.ToolChain
2671 self
._Macro
["TOOLCHAIN_TAG" ] = self
.ToolChain
2672 self
._Macro
["TOOL_CHAIN_TAG" ] = self
.ToolChain
2673 self
._Macro
["TARGET" ] = self
.BuildTarget
2675 self
._Macro
["BUILD_DIR" ] = self
.PlatformInfo
.BuildDir
2676 self
._Macro
["BIN_DIR" ] = os
.path
.join(self
.PlatformInfo
.BuildDir
, self
.Arch
)
2677 self
._Macro
["LIB_DIR" ] = os
.path
.join(self
.PlatformInfo
.BuildDir
, self
.Arch
)
2678 self
._Macro
["MODULE_BUILD_DIR" ] = self
.BuildDir
2679 self
._Macro
["OUTPUT_DIR" ] = self
.OutputDir
2680 self
._Macro
["DEBUG_DIR" ] = self
.DebugDir
2681 self
._Macro
["DEST_DIR_OUTPUT" ] = self
.OutputDir
2682 self
._Macro
["DEST_DIR_DEBUG" ] = self
.DebugDir
2683 self
._Macro
["PLATFORM_NAME" ] = self
.PlatformInfo
.Name
2684 self
._Macro
["PLATFORM_GUID" ] = self
.PlatformInfo
.Guid
2685 self
._Macro
["PLATFORM_VERSION" ] = self
.PlatformInfo
.Version
2686 self
._Macro
["PLATFORM_RELATIVE_DIR" ] = self
.PlatformInfo
.SourceDir
2687 self
._Macro
["PLATFORM_DIR" ] = mws
.join(self
.WorkspaceDir
, self
.PlatformInfo
.SourceDir
)
2688 self
._Macro
["PLATFORM_OUTPUT_DIR" ] = self
.PlatformInfo
.OutputDir
2691 ## Return the module build data object
2692 def _GetModule(self
):
2693 if self
._Module
== None:
2694 self
._Module
= self
.Workspace
.BuildDatabase
[self
.MetaFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
2697 ## Return the module name
2698 def _GetBaseName(self
):
2699 return self
.Module
.BaseName
2701 ## Return the module DxsFile if exist
2702 def _GetDxsFile(self
):
2703 return self
.Module
.DxsFile
2705 ## Return the module SourceOverridePath
2706 def _GetSourceOverridePath(self
):
2707 return self
.Module
.SourceOverridePath
2709 ## Return the module meta-file GUID
2712 # To build same module more than once, the module path with FILE_GUID overridden has
2713 # the file name FILE_GUIDmodule.inf, but the relative path (self.MetaFile.File) is the realy path
2714 # in DSC. The overridden GUID can be retrieved from file name
2716 if os
.path
.basename(self
.MetaFile
.File
) != os
.path
.basename(self
.MetaFile
.Path
):
2718 # Length of GUID is 36
2720 return os
.path
.basename(self
.MetaFile
.Path
)[:36]
2721 return self
.Module
.Guid
2723 ## Return the module version
2724 def _GetVersion(self
):
2725 return self
.Module
.Version
2727 ## Return the module type
2728 def _GetModuleType(self
):
2729 return self
.Module
.ModuleType
2731 ## Return the component type (for Edk.x style of module)
2732 def _GetComponentType(self
):
2733 return self
.Module
.ComponentType
2735 ## Return the build type
2736 def _GetBuildType(self
):
2737 return self
.Module
.BuildType
2739 ## Return the PCD_IS_DRIVER setting
2740 def _GetPcdIsDriver(self
):
2741 return self
.Module
.PcdIsDriver
2743 ## Return the autogen version, i.e. module meta-file version
2744 def _GetAutoGenVersion(self
):
2745 return self
.Module
.AutoGenVersion
2747 ## Check if the module is library or not
2748 def _IsLibrary(self
):
2749 if self
._LibraryFlag
== None:
2750 if self
.Module
.LibraryClass
!= None and self
.Module
.LibraryClass
!= []:
2751 self
._LibraryFlag
= True
2753 self
._LibraryFlag
= False
2754 return self
._LibraryFlag
2756 ## Check if the module is binary module or not
2757 def _IsBinaryModule(self
):
2758 return self
.Module
.IsBinaryModule
2760 ## Return the directory to store intermediate files of the module
2761 def _GetBuildDir(self
):
2762 if self
._BuildDir
== None:
2763 self
._BuildDir
= path
.join(
2764 self
.PlatformInfo
.BuildDir
,
2767 self
.MetaFile
.BaseName
2769 CreateDirectory(self
._BuildDir
)
2770 return self
._BuildDir
2772 ## Return the directory to store the intermediate object files of the mdoule
2773 def _GetOutputDir(self
):
2774 if self
._OutputDir
== None:
2775 self
._OutputDir
= path
.join(self
.BuildDir
, "OUTPUT")
2776 CreateDirectory(self
._OutputDir
)
2777 return self
._OutputDir
2779 ## Return the directory to store auto-gened source files of the mdoule
2780 def _GetDebugDir(self
):
2781 if self
._DebugDir
== None:
2782 self
._DebugDir
= path
.join(self
.BuildDir
, "DEBUG")
2783 CreateDirectory(self
._DebugDir
)
2784 return self
._DebugDir
2786 ## Return the path of custom file
2787 def _GetCustomMakefile(self
):
2788 if self
._CustomMakefile
== None:
2789 self
._CustomMakefile
= {}
2790 for Type
in self
.Module
.CustomMakefile
:
2791 if Type
in gMakeTypeMap
:
2792 MakeType
= gMakeTypeMap
[Type
]
2795 if self
.SourceOverrideDir
!= None:
2796 File
= os
.path
.join(self
.SourceOverrideDir
, self
.Module
.CustomMakefile
[Type
])
2797 if not os
.path
.exists(File
):
2798 File
= os
.path
.join(self
.SourceDir
, self
.Module
.CustomMakefile
[Type
])
2800 File
= os
.path
.join(self
.SourceDir
, self
.Module
.CustomMakefile
[Type
])
2801 self
._CustomMakefile
[MakeType
] = File
2802 return self
._CustomMakefile
2804 ## Return the directory of the makefile
2806 # @retval string The directory string of module's makefile
2808 def _GetMakeFileDir(self
):
2809 return self
.BuildDir
2811 ## Return build command string
2813 # @retval string Build command string
2815 def _GetBuildCommand(self
):
2816 return self
.PlatformInfo
.BuildCommand
2818 ## Get object list of all packages the module and its dependent libraries belong to
2820 # @retval list The list of package object
2822 def _GetDerivedPackageList(self
):
2824 for M
in [self
.Module
] + self
.DependentLibraryList
:
2825 for Package
in M
.Packages
:
2826 if Package
in PackageList
:
2828 PackageList
.append(Package
)
2831 ## Get the depex string
2833 # @return : a string contain all depex expresion.
2834 def _GetDepexExpresionString(self
):
2837 ## DPX_SOURCE IN Define section.
2838 if self
.Module
.DxsFile
:
2840 for M
in [self
.Module
] + self
.DependentLibraryList
:
2841 Filename
= M
.MetaFile
.Path
2842 InfObj
= InfSectionParser
.InfSectionParser(Filename
)
2843 DepexExpresionList
= InfObj
.GetDepexExpresionList()
2844 for DepexExpresion
in DepexExpresionList
:
2845 for key
in DepexExpresion
.keys():
2846 Arch
, ModuleType
= key
2847 DepexExpr
= [x
for x
in DepexExpresion
[key
] if not str(x
).startswith('#')]
2848 # the type of build module is USER_DEFINED.
2849 # All different DEPEX section tags would be copied into the As Built INF file
2850 # and there would be separate DEPEX section tags
2851 if self
.ModuleType
.upper() == SUP_MODULE_USER_DEFINED
:
2852 if (Arch
.upper() == self
.Arch
.upper()) and (ModuleType
.upper() != TAB_ARCH_COMMON
):
2853 DepexList
.append({(Arch
, ModuleType
): DepexExpr
})
2855 if Arch
.upper() == TAB_ARCH_COMMON
or \
2856 (Arch
.upper() == self
.Arch
.upper() and \
2857 ModuleType
.upper() in [TAB_ARCH_COMMON
, self
.ModuleType
.upper()]):
2858 DepexList
.append({(Arch
, ModuleType
): DepexExpr
})
2860 #the type of build module is USER_DEFINED.
2861 if self
.ModuleType
.upper() == SUP_MODULE_USER_DEFINED
:
2862 for Depex
in DepexList
:
2863 for key
in Depex
.keys():
2864 DepexStr
+= '[Depex.%s.%s]\n' % key
2865 DepexStr
+= '\n'.join(['# '+ val
for val
in Depex
[key
]])
2868 return '[Depex.%s]\n' % self
.Arch
2871 #the type of build module not is USER_DEFINED.
2873 for Depex
in DepexList
:
2878 for D
in Depex
.values():
2879 DepexStr
+= ' '.join([val
for val
in D
])
2880 Index
= DepexStr
.find('END')
2881 if Index
> -1 and Index
== len(DepexStr
) - 3:
2882 DepexStr
= DepexStr
[:-3]
2883 DepexStr
= DepexStr
.strip()
2886 DepexStr
= DepexStr
.lstrip('(').rstrip(')').strip()
2888 return '[Depex.%s]\n' % self
.Arch
2889 return '[Depex.%s]\n# ' % self
.Arch
+ DepexStr
2891 ## Merge dependency expression
2893 # @retval list The token list of the dependency expression after parsed
2895 def _GetDepexTokenList(self
):
2896 if self
._DepexList
== None:
2897 self
._DepexList
= {}
2898 if self
.DxsFile
or self
.IsLibrary
or TAB_DEPENDENCY_EXPRESSION_FILE
in self
.FileTypes
:
2899 return self
._DepexList
2901 self
._DepexList
[self
.ModuleType
] = []
2903 for ModuleType
in self
._DepexList
:
2904 DepexList
= self
._DepexList
[ModuleType
]
2906 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion
2908 for M
in [self
.Module
] + self
.DependentLibraryList
:
2910 for D
in M
.Depex
[self
.Arch
, ModuleType
]:
2912 DepexList
.append('AND')
2913 DepexList
.append('(')
2915 if DepexList
[-1] == 'END': # no need of a END at this time
2917 DepexList
.append(')')
2920 EdkLogger
.verbose("DEPEX[%s] (+%s) = %s" % (self
.Name
, M
.BaseName
, DepexList
))
2921 if 'BEFORE' in DepexList
or 'AFTER' in DepexList
:
2923 if len(DepexList
) > 0:
2924 EdkLogger
.verbose('')
2925 return self
._DepexList
2927 ## Merge dependency expression
2929 # @retval list The token list of the dependency expression after parsed
2931 def _GetDepexExpressionTokenList(self
):
2932 if self
._DepexExpressionList
== None:
2933 self
._DepexExpressionList
= {}
2934 if self
.DxsFile
or self
.IsLibrary
or TAB_DEPENDENCY_EXPRESSION_FILE
in self
.FileTypes
:
2935 return self
._DepexExpressionList
2937 self
._DepexExpressionList
[self
.ModuleType
] = ''
2939 for ModuleType
in self
._DepexExpressionList
:
2940 DepexExpressionList
= self
._DepexExpressionList
[ModuleType
]
2942 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion
2944 for M
in [self
.Module
] + self
.DependentLibraryList
:
2946 for D
in M
.DepexExpression
[self
.Arch
, ModuleType
]:
2947 if DepexExpressionList
!= '':
2948 DepexExpressionList
+= ' AND '
2949 DepexExpressionList
+= '('
2950 DepexExpressionList
+= D
2951 DepexExpressionList
= DepexExpressionList
.rstrip('END').strip()
2952 DepexExpressionList
+= ')'
2955 EdkLogger
.verbose("DEPEX[%s] (+%s) = %s" % (self
.Name
, M
.BaseName
, DepexExpressionList
))
2956 if 'BEFORE' in DepexExpressionList
or 'AFTER' in DepexExpressionList
:
2958 if len(DepexExpressionList
) > 0:
2959 EdkLogger
.verbose('')
2960 self
._DepexExpressionList
[ModuleType
] = DepexExpressionList
2961 return self
._DepexExpressionList
2963 ## Return the list of specification version required for the module
2965 # @retval list The list of specification defined in module file
2967 def _GetSpecification(self
):
2968 return self
.Module
.Specification
2970 ## Tool option for the module build
2972 # @param PlatformInfo The object of PlatformBuildInfo
2973 # @retval dict The dict containing valid options
2975 def _GetModuleBuildOption(self
):
2976 if self
._BuildOption
== None:
2977 self
._BuildOption
, self
.BuildRuleOrder
= self
.PlatformInfo
.ApplyBuildOption(self
.Module
)
2978 if self
.BuildRuleOrder
:
2979 self
.BuildRuleOrder
= ['.%s' % Ext
for Ext
in self
.BuildRuleOrder
.split()]
2980 return self
._BuildOption
2982 ## Get include path list from tool option for the module build
2984 # @retval list The include path list
2986 def _GetBuildOptionIncPathList(self
):
2987 if self
._BuildOptionIncPathList
== None:
2989 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT
2990 # is the former use /I , the Latter used -I to specify include directories
2992 if self
.PlatformInfo
.ToolChainFamily
in ('MSFT'):
2993 gBuildOptIncludePattern
= re
.compile(r
"(?:.*?)/I[ \t]*([^ ]*)", re
.MULTILINE | re
.DOTALL
)
2994 elif self
.PlatformInfo
.ToolChainFamily
in ('INTEL', 'GCC', 'RVCT'):
2995 gBuildOptIncludePattern
= re
.compile(r
"(?:.*?)-I[ \t]*([^ ]*)", re
.MULTILINE | re
.DOTALL
)
2998 # New ToolChainFamily, don't known whether there is option to specify include directories
3000 self
._BuildOptionIncPathList
= []
3001 return self
._BuildOptionIncPathList
3003 BuildOptionIncPathList
= []
3004 for Tool
in ('CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'ASM'):
3007 FlagOption
= self
.BuildOption
[Tool
][Attr
]
3011 if self
.PlatformInfo
.ToolChainFamily
!= 'RVCT':
3012 IncPathList
= [NormPath(Path
, self
.Macros
) for Path
in gBuildOptIncludePattern
.findall(FlagOption
)]
3015 # RVCT may specify a list of directory seperated by commas
3018 for Path
in gBuildOptIncludePattern
.findall(FlagOption
):
3019 PathList
= GetSplitList(Path
, TAB_COMMA_SPLIT
)
3020 IncPathList
+= [NormPath(PathEntry
, self
.Macros
) for PathEntry
in PathList
]
3023 # EDK II modules must not reference header files outside of the packages they depend on or
3024 # within the module's directory tree. Report error if violation.
3026 if self
.AutoGenVersion
>= 0x00010005 and len(IncPathList
) > 0:
3027 for Path
in IncPathList
:
3028 if (Path
not in self
.IncludePathList
) and (CommonPath([Path
, self
.MetaFile
.Dir
]) != self
.MetaFile
.Dir
):
3029 ErrMsg
= "The include directory for the EDK II module in this line is invalid %s specified in %s FLAGS '%s'" % (Path
, Tool
, FlagOption
)
3030 EdkLogger
.error("build",
3033 File
=str(self
.MetaFile
))
3036 BuildOptionIncPathList
+= IncPathList
3038 self
._BuildOptionIncPathList
= BuildOptionIncPathList
3040 return self
._BuildOptionIncPathList
3042 ## Return a list of files which can be built from source
3044 # What kind of files can be built is determined by build rules in
3045 # $(CONF_DIRECTORY)/build_rule.txt and toolchain family.
3047 def _GetSourceFileList(self
):
3048 if self
._SourceFileList
== None:
3049 self
._SourceFileList
= []
3050 for F
in self
.Module
.Sources
:
3052 if F
.TagName
not in ("", "*", self
.ToolChain
):
3053 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "The toolchain [%s] for processing file [%s] is found, "
3054 "but [%s] is needed" % (F
.TagName
, str(F
), self
.ToolChain
))
3056 # match tool chain family
3057 if F
.ToolChainFamily
not in ("", "*", self
.ToolChainFamily
):
3060 "The file [%s] must be built by tools of [%s], " \
3061 "but current toolchain family is [%s]" \
3062 % (str(F
), F
.ToolChainFamily
, self
.ToolChainFamily
))
3065 # add the file path into search path list for file including
3066 if F
.Dir
not in self
.IncludePathList
and self
.AutoGenVersion
>= 0x00010005:
3067 self
.IncludePathList
.insert(0, F
.Dir
)
3068 self
._SourceFileList
.append(F
)
3070 self
._MatchBuildRuleOrder
(self
._SourceFileList
)
3072 for F
in self
._SourceFileList
:
3073 self
._ApplyBuildRule
(F
, TAB_UNKNOWN_FILE
)
3074 return self
._SourceFileList
3076 def _MatchBuildRuleOrder(self
, FileList
):
3078 self
._GetModuleBuildOption
()
3079 for SingleFile
in FileList
:
3080 if self
.BuildRuleOrder
and SingleFile
.Ext
in self
.BuildRuleOrder
and SingleFile
.Ext
in self
.BuildRules
:
3081 key
= SingleFile
.Path
.split(SingleFile
.Ext
)[0]
3082 if key
in Order_Dict
:
3083 Order_Dict
[key
].append(SingleFile
.Ext
)
3085 Order_Dict
[key
] = [SingleFile
.Ext
]
3088 for F
in Order_Dict
:
3089 if len(Order_Dict
[F
]) > 1:
3090 Order_Dict
[F
].sort(key
=lambda i
: self
.BuildRuleOrder
.index(i
))
3091 for Ext
in Order_Dict
[F
][1:]:
3092 RemoveList
.append(F
+ Ext
)
3094 for item
in RemoveList
:
3095 FileList
.remove(item
)
3099 ## Return the list of unicode files
3100 def _GetUnicodeFileList(self
):
3101 if self
._UnicodeFileList
== None:
3102 if TAB_UNICODE_FILE
in self
.FileTypes
:
3103 self
._UnicodeFileList
= self
.FileTypes
[TAB_UNICODE_FILE
]
3105 self
._UnicodeFileList
= []
3106 return self
._UnicodeFileList
3108 ## Return a list of files which can be built from binary
3110 # "Build" binary files are just to copy them to build directory.
3112 # @retval list The list of files which can be built later
3114 def _GetBinaryFiles(self
):
3115 if self
._BinaryFileList
== None:
3116 self
._BinaryFileList
= []
3117 for F
in self
.Module
.Binaries
:
3118 if F
.Target
not in ['COMMON', '*'] and F
.Target
!= self
.BuildTarget
:
3120 self
._BinaryFileList
.append(F
)
3121 self
._ApplyBuildRule
(F
, F
.Type
)
3122 return self
._BinaryFileList
3124 def _GetBuildRules(self
):
3125 if self
._BuildRules
== None:
3127 BuildRuleDatabase
= self
.PlatformInfo
.BuildRule
3128 for Type
in BuildRuleDatabase
.FileTypeList
:
3129 #first try getting build rule by BuildRuleFamily
3130 RuleObject
= BuildRuleDatabase
[Type
, self
.BuildType
, self
.Arch
, self
.BuildRuleFamily
]
3132 # build type is always module type, but ...
3133 if self
.ModuleType
!= self
.BuildType
:
3134 RuleObject
= BuildRuleDatabase
[Type
, self
.ModuleType
, self
.Arch
, self
.BuildRuleFamily
]
3135 #second try getting build rule by ToolChainFamily
3137 RuleObject
= BuildRuleDatabase
[Type
, self
.BuildType
, self
.Arch
, self
.ToolChainFamily
]
3139 # build type is always module type, but ...
3140 if self
.ModuleType
!= self
.BuildType
:
3141 RuleObject
= BuildRuleDatabase
[Type
, self
.ModuleType
, self
.Arch
, self
.ToolChainFamily
]
3144 RuleObject
= RuleObject
.Instantiate(self
.Macros
)
3145 BuildRules
[Type
] = RuleObject
3146 for Ext
in RuleObject
.SourceFileExtList
:
3147 BuildRules
[Ext
] = RuleObject
3148 self
._BuildRules
= BuildRules
3149 return self
._BuildRules
3151 def _ApplyBuildRule(self
, File
, FileType
):
3152 if self
._BuildTargets
== None:
3153 self
._IntroBuildTargetList
= set()
3154 self
._FinalBuildTargetList
= set()
3155 self
._BuildTargets
= {}
3156 self
._FileTypes
= {}
3158 SubDirectory
= os
.path
.join(self
.OutputDir
, File
.SubDir
)
3159 if not os
.path
.exists(SubDirectory
):
3160 CreateDirectory(SubDirectory
)
3166 # Make sure to get build rule order value
3168 self
._GetModuleBuildOption
()
3170 while Index
< len(SourceList
):
3171 Source
= SourceList
[Index
]
3175 CreateDirectory(Source
.Dir
)
3177 if File
.IsBinary
and File
== Source
and self
._BinaryFileList
!= None and File
in self
._BinaryFileList
:
3178 # Skip all files that are not binary libraries
3179 if not self
.IsLibrary
:
3181 RuleObject
= self
.BuildRules
[TAB_DEFAULT_BINARY_FILE
]
3182 elif FileType
in self
.BuildRules
:
3183 RuleObject
= self
.BuildRules
[FileType
]
3184 elif Source
.Ext
in self
.BuildRules
:
3185 RuleObject
= self
.BuildRules
[Source
.Ext
]
3187 # stop at no more rules
3189 self
._FinalBuildTargetList
.add(LastTarget
)
3192 FileType
= RuleObject
.SourceFileType
3193 if FileType
not in self
._FileTypes
:
3194 self
._FileTypes
[FileType
] = set()
3195 self
._FileTypes
[FileType
].add(Source
)
3197 # stop at STATIC_LIBRARY for library
3198 if self
.IsLibrary
and FileType
== TAB_STATIC_LIBRARY
:
3200 self
._FinalBuildTargetList
.add(LastTarget
)
3203 Target
= RuleObject
.Apply(Source
, self
.BuildRuleOrder
)
3206 self
._FinalBuildTargetList
.add(LastTarget
)
3208 elif not Target
.Outputs
:
3209 # Only do build for target with outputs
3210 self
._FinalBuildTargetList
.add(Target
)
3212 if FileType
not in self
._BuildTargets
:
3213 self
._BuildTargets
[FileType
] = set()
3214 self
._BuildTargets
[FileType
].add(Target
)
3216 if not Source
.IsBinary
and Source
== File
:
3217 self
._IntroBuildTargetList
.add(Target
)
3219 # to avoid cyclic rule
3220 if FileType
in RuleChain
:
3223 RuleChain
.append(FileType
)
3224 SourceList
.extend(Target
.Outputs
)
3226 FileType
= TAB_UNKNOWN_FILE
3228 def _GetTargets(self
):
3229 if self
._BuildTargets
== None:
3230 self
._IntroBuildTargetList
= set()
3231 self
._FinalBuildTargetList
= set()
3232 self
._BuildTargets
= {}
3233 self
._FileTypes
= {}
3235 #TRICK: call _GetSourceFileList to apply build rule for source files
3236 if self
.SourceFileList
:
3239 #TRICK: call _GetBinaryFileList to apply build rule for binary files
3240 if self
.BinaryFileList
:
3243 return self
._BuildTargets
3245 def _GetIntroTargetList(self
):
3247 return self
._IntroBuildTargetList
3249 def _GetFinalTargetList(self
):
3251 return self
._FinalBuildTargetList
3253 def _GetFileTypes(self
):
3255 return self
._FileTypes
3257 ## Get the list of package object the module depends on
3259 # @retval list The package object list
3261 def _GetDependentPackageList(self
):
3262 return self
.Module
.Packages
3264 ## Return the list of auto-generated code file
3266 # @retval list The list of auto-generated file
3268 def _GetAutoGenFileList(self
):
3269 UniStringAutoGenC
= True
3270 UniStringBinBuffer
= StringIO()
3271 if self
.BuildType
== 'UEFI_HII':
3272 UniStringAutoGenC
= False
3273 if self
._AutoGenFileList
== None:
3274 self
._AutoGenFileList
= {}
3275 AutoGenC
= TemplateString()
3276 AutoGenH
= TemplateString()
3277 StringH
= TemplateString()
3278 GenC
.CreateCode(self
, AutoGenC
, AutoGenH
, StringH
, UniStringAutoGenC
, UniStringBinBuffer
)
3280 # AutoGen.c is generated if there are library classes in inf, or there are object files
3282 if str(AutoGenC
) != "" and (len(self
.Module
.LibraryClasses
) > 0
3283 or TAB_OBJECT_FILE
in self
.FileTypes
):
3284 AutoFile
= PathClass(gAutoGenCodeFileName
, self
.DebugDir
)
3285 self
._AutoGenFileList
[AutoFile
] = str(AutoGenC
)
3286 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3287 if str(AutoGenH
) != "":
3288 AutoFile
= PathClass(gAutoGenHeaderFileName
, self
.DebugDir
)
3289 self
._AutoGenFileList
[AutoFile
] = str(AutoGenH
)
3290 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3291 if str(StringH
) != "":
3292 AutoFile
= PathClass(gAutoGenStringFileName
% {"module_name":self
.Name
}, self
.DebugDir
)
3293 self
._AutoGenFileList
[AutoFile
] = str(StringH
)
3294 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3295 if UniStringBinBuffer
!= None and UniStringBinBuffer
.getvalue() != "":
3296 AutoFile
= PathClass(gAutoGenStringFormFileName
% {"module_name":self
.Name
}, self
.OutputDir
)
3297 self
._AutoGenFileList
[AutoFile
] = UniStringBinBuffer
.getvalue()
3298 AutoFile
.IsBinary
= True
3299 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3300 if UniStringBinBuffer
!= None:
3301 UniStringBinBuffer
.close()
3302 return self
._AutoGenFileList
3304 ## Return the list of library modules explicitly or implicityly used by this module
3305 def _GetLibraryList(self
):
3306 if self
._DependentLibraryList
== None:
3307 # only merge library classes and PCD for non-library module
3309 self
._DependentLibraryList
= []
3311 if self
.AutoGenVersion
< 0x00010005:
3312 self
._DependentLibraryList
= self
.PlatformInfo
.ResolveLibraryReference(self
.Module
)
3314 self
._DependentLibraryList
= self
.PlatformInfo
.ApplyLibraryInstance(self
.Module
)
3315 return self
._DependentLibraryList
3318 def UpdateComments(Recver
, Src
):
3320 if Key
not in Recver
:
3322 Recver
[Key
].extend(Src
[Key
])
3323 ## Get the list of PCDs from current module
3325 # @retval list The list of PCD
3327 def _GetModulePcdList(self
):
3328 if self
._ModulePcdList
== None:
3329 # apply PCD settings from platform
3330 self
._ModulePcdList
= self
.PlatformInfo
.ApplyPcdSetting(self
.Module
, self
.Module
.Pcds
)
3331 self
.UpdateComments(self
._PcdComments
, self
.Module
.PcdComments
)
3332 return self
._ModulePcdList
3334 ## Get the list of PCDs from dependent libraries
3336 # @retval list The list of PCD
3338 def _GetLibraryPcdList(self
):
3339 if self
._LibraryPcdList
== None:
3341 if not self
.IsLibrary
:
3342 # get PCDs from dependent libraries
3343 for Library
in self
.DependentLibraryList
:
3344 self
.UpdateComments(self
._PcdComments
, Library
.PcdComments
)
3345 for Key
in Library
.Pcds
:
3346 # skip duplicated PCDs
3347 if Key
in self
.Module
.Pcds
or Key
in Pcds
:
3349 Pcds
[Key
] = copy
.copy(Library
.Pcds
[Key
])
3350 # apply PCD settings from platform
3351 self
._LibraryPcdList
= self
.PlatformInfo
.ApplyPcdSetting(self
.Module
, Pcds
)
3353 self
._LibraryPcdList
= []
3354 return self
._LibraryPcdList
3356 ## Get the GUID value mapping
3358 # @retval dict The mapping between GUID cname and its value
3360 def _GetGuidList(self
):
3361 if self
._GuidList
== None:
3362 self
._GuidList
= sdict()
3363 self
._GuidList
.update(self
.Module
.Guids
)
3364 for Library
in self
.DependentLibraryList
:
3365 self
._GuidList
.update(Library
.Guids
)
3366 self
.UpdateComments(self
._GuidComments
, Library
.GuidComments
)
3367 self
.UpdateComments(self
._GuidComments
, self
.Module
.GuidComments
)
3368 return self
._GuidList
3370 def GetGuidsUsedByPcd(self
):
3371 if self
._GuidsUsedByPcd
== None:
3372 self
._GuidsUsedByPcd
= sdict()
3373 self
._GuidsUsedByPcd
.update(self
.Module
.GetGuidsUsedByPcd())
3374 for Library
in self
.DependentLibraryList
:
3375 self
._GuidsUsedByPcd
.update(Library
.GetGuidsUsedByPcd())
3376 return self
._GuidsUsedByPcd
3377 ## Get the protocol value mapping
3379 # @retval dict The mapping between protocol cname and its value
3381 def _GetProtocolList(self
):
3382 if self
._ProtocolList
== None:
3383 self
._ProtocolList
= sdict()
3384 self
._ProtocolList
.update(self
.Module
.Protocols
)
3385 for Library
in self
.DependentLibraryList
:
3386 self
._ProtocolList
.update(Library
.Protocols
)
3387 self
.UpdateComments(self
._ProtocolComments
, Library
.ProtocolComments
)
3388 self
.UpdateComments(self
._ProtocolComments
, self
.Module
.ProtocolComments
)
3389 return self
._ProtocolList
3391 ## Get the PPI value mapping
3393 # @retval dict The mapping between PPI cname and its value
3395 def _GetPpiList(self
):
3396 if self
._PpiList
== None:
3397 self
._PpiList
= sdict()
3398 self
._PpiList
.update(self
.Module
.Ppis
)
3399 for Library
in self
.DependentLibraryList
:
3400 self
._PpiList
.update(Library
.Ppis
)
3401 self
.UpdateComments(self
._PpiComments
, Library
.PpiComments
)
3402 self
.UpdateComments(self
._PpiComments
, self
.Module
.PpiComments
)
3403 return self
._PpiList
3405 ## Get the list of include search path
3407 # @retval list The list path
3409 def _GetIncludePathList(self
):
3410 if self
._IncludePathList
== None:
3411 self
._IncludePathList
= []
3412 if self
.AutoGenVersion
< 0x00010005:
3413 for Inc
in self
.Module
.Includes
:
3414 if Inc
not in self
._IncludePathList
:
3415 self
._IncludePathList
.append(Inc
)
3417 Inc
= path
.join(Inc
, self
.Arch
.capitalize())
3418 if os
.path
.exists(Inc
) and Inc
not in self
._IncludePathList
:
3419 self
._IncludePathList
.append(Inc
)
3420 # Edk module needs to put DEBUG_DIR at the end of search path and not to use SOURCE_DIR all the time
3421 self
._IncludePathList
.append(self
.DebugDir
)
3423 self
._IncludePathList
.append(self
.MetaFile
.Dir
)
3424 self
._IncludePathList
.append(self
.DebugDir
)
3426 for Package
in self
.Module
.Packages
:
3427 PackageDir
= mws
.join(self
.WorkspaceDir
, Package
.MetaFile
.Dir
)
3428 if PackageDir
not in self
._IncludePathList
:
3429 self
._IncludePathList
.append(PackageDir
)
3430 IncludesList
= Package
.Includes
3431 if Package
._PrivateIncludes
:
3432 if not self
.MetaFile
.Path
.startswith(PackageDir
):
3433 IncludesList
= list(set(Package
.Includes
).difference(set(Package
._PrivateIncludes
)))
3434 for Inc
in IncludesList
:
3435 if Inc
not in self
._IncludePathList
:
3436 self
._IncludePathList
.append(str(Inc
))
3437 return self
._IncludePathList
3439 def _GetIncludePathLength(self
):
3440 self
._IncludePathLength
= 0
3441 if self
._IncludePathList
:
3442 for inc
in self
._IncludePathList
:
3443 self
._IncludePathLength
+= len(' ' + inc
)
3444 return self
._IncludePathLength
3446 ## Get HII EX PCDs which maybe used by VFR
3448 # efivarstore used by VFR may relate with HII EX PCDs
3449 # Get the variable name and GUID from efivarstore and HII EX PCD
3450 # List the HII EX PCDs in As Built INF if both name and GUID match.
3452 # @retval list HII EX PCDs
3454 def _GetPcdsMaybeUsedByVfr(self
):
3455 if not self
.SourceFileList
:
3459 for SrcFile
in self
.SourceFileList
:
3460 if SrcFile
.Ext
.lower() != '.vfr':
3462 Vfri
= os
.path
.join(self
.OutputDir
, SrcFile
.BaseName
+ '.i')
3463 if not os
.path
.exists(Vfri
):
3465 VfriFile
= open(Vfri
, 'r')
3466 Content
= VfriFile
.read()
3468 Pos
= Content
.find('efivarstore')
3471 # Make sure 'efivarstore' is the start of efivarstore statement
3472 # In case of the value of 'name' (name = efivarstore) is equal to 'efivarstore'
3475 while Index
>= 0 and Content
[Index
] in ' \t\r\n':
3477 if Index
>= 0 and Content
[Index
] != ';':
3478 Pos
= Content
.find('efivarstore', Pos
+ len('efivarstore'))
3481 # 'efivarstore' must be followed by name and guid
3483 Name
= gEfiVarStoreNamePattern
.search(Content
, Pos
)
3486 Guid
= gEfiVarStoreGuidPattern
.search(Content
, Pos
)
3489 NameArray
= ConvertStringToByteArray('L"' + Name
.group(1) + '"')
3490 NameGuids
.append((NameArray
, GuidStructureStringToGuidString(Guid
.group(1))))
3491 Pos
= Content
.find('efivarstore', Name
.end())
3495 for Pcd
in self
.PlatformInfo
.Platform
.Pcds
.values():
3496 if Pcd
.Type
!= TAB_PCDS_DYNAMIC_EX_HII
:
3498 for SkuName
in Pcd
.SkuInfoList
:
3499 SkuInfo
= Pcd
.SkuInfoList
[SkuName
]
3500 Name
= ConvertStringToByteArray(SkuInfo
.VariableName
)
3501 Value
= GuidValue(SkuInfo
.VariableGuid
, self
.PlatformInfo
.PackageList
, self
.MetaFile
.Path
)
3504 Guid
= GuidStructureStringToGuidString(Value
)
3505 if (Name
, Guid
) in NameGuids
and Pcd
not in HiiExPcds
:
3506 HiiExPcds
.append(Pcd
)
3511 def _GenOffsetBin(self
):
3513 for SourceFile
in self
.Module
.Sources
:
3514 if SourceFile
.Type
.upper() == ".VFR" :
3516 # search the .map file to find the offset of vfr binary in the PE32+/TE file.
3518 VfrUniBaseName
[SourceFile
.BaseName
] = (SourceFile
.BaseName
+ "Bin")
3519 if SourceFile
.Type
.upper() == ".UNI" :
3521 # search the .map file to find the offset of Uni strings binary in the PE32+/TE file.
3523 VfrUniBaseName
["UniOffsetName"] = (self
.Name
+ "Strings")
3525 if len(VfrUniBaseName
) == 0:
3527 MapFileName
= os
.path
.join(self
.OutputDir
, self
.Name
+ ".map")
3528 EfiFileName
= os
.path
.join(self
.OutputDir
, self
.Name
+ ".efi")
3529 VfrUniOffsetList
= GetVariableOffset(MapFileName
, EfiFileName
, VfrUniBaseName
.values())
3530 if not VfrUniOffsetList
:
3533 OutputName
= '%sOffset.bin' % self
.Name
3534 UniVfrOffsetFileName
= os
.path
.join( self
.OutputDir
, OutputName
)
3537 fInputfile
= open(UniVfrOffsetFileName
, "wb+", 0)
3539 EdkLogger
.error("build", FILE_OPEN_FAILURE
, "File open failed for %s" % UniVfrOffsetFileName
,None)
3541 # Use a instance of StringIO to cache data
3542 fStringIO
= StringIO('')
3544 for Item
in VfrUniOffsetList
:
3545 if (Item
[0].find("Strings") != -1):
3547 # UNI offset in image.
3549 # { 0x8913c5e0, 0x33f6, 0x4d86, { 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66 } }
3551 UniGuid
= [0xe0, 0xc5, 0x13, 0x89, 0xf6, 0x33, 0x86, 0x4d, 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66]
3552 UniGuid
= [chr(ItemGuid
) for ItemGuid
in UniGuid
]
3553 fStringIO
.write(''.join(UniGuid
))
3554 UniValue
= pack ('Q', int (Item
[1], 16))
3555 fStringIO
.write (UniValue
)
3558 # VFR binary offset in image.
3560 # { 0xd0bc7cb4, 0x6a47, 0x495f, { 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2 } };
3562 VfrGuid
= [0xb4, 0x7c, 0xbc, 0xd0, 0x47, 0x6a, 0x5f, 0x49, 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2]
3563 VfrGuid
= [chr(ItemGuid
) for ItemGuid
in VfrGuid
]
3564 fStringIO
.write(''.join(VfrGuid
))
3566 VfrValue
= pack ('Q', int (Item
[1], 16))
3567 fStringIO
.write (VfrValue
)
3569 # write data into file.
3572 fInputfile
.write (fStringIO
.getvalue())
3574 EdkLogger
.error("build", FILE_WRITE_FAILURE
, "Write data to file %s failed, please check whether the "
3575 "file been locked or using by other applications." %UniVfrOffsetFileName
,None)
3581 ## Create AsBuilt INF file the module
3583 def CreateAsBuiltInf(self
):
3584 if self
.IsAsBuiltInfCreated
:
3587 # Skip the following code for EDK I inf
3588 if self
.AutoGenVersion
< 0x00010005:
3591 # Skip the following code for libraries
3595 # Skip the following code for modules with no source files
3596 if self
.SourceFileList
== None or self
.SourceFileList
== []:
3599 # Skip the following code for modules without any binary files
3600 if self
.BinaryFileList
<> None and self
.BinaryFileList
<> []:
3603 ### TODO: How to handles mixed source and binary modules
3605 # Find all DynamicEx and PatchableInModule PCDs used by this module and dependent libraries
3606 # Also find all packages that the DynamicEx PCDs depend on
3611 PcdTokenSpaceList
= []
3612 for Pcd
in self
.ModulePcdList
+ self
.LibraryPcdList
:
3613 if Pcd
.Type
== TAB_PCDS_PATCHABLE_IN_MODULE
:
3614 PatchablePcds
[Pcd
.TokenCName
] = Pcd
3615 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, 'PatchableInModule'))
3616 elif Pcd
.Type
in GenC
.gDynamicExPcd
:
3619 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, 'DynamicEx'))
3620 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, 'Dynamic'))
3621 PcdTokenSpaceList
.append(Pcd
.TokenSpaceGuidCName
)
3623 GuidList
.update(self
.GuidList
)
3624 for TokenSpace
in self
.GetGuidsUsedByPcd():
3625 # If token space is not referred by patch PCD or Ex PCD, remove the GUID from GUID list
3626 # The GUIDs in GUIDs section should really be the GUIDs in source INF or referred by Ex an patch PCDs
3627 if TokenSpace
not in PcdTokenSpaceList
and TokenSpace
in GuidList
:
3628 GuidList
.pop(TokenSpace
)
3629 CheckList
= (GuidList
, self
.PpiList
, self
.ProtocolList
, PcdCheckList
)
3630 for Package
in self
.DerivedPackageList
:
3631 if Package
in Packages
:
3633 BeChecked
= (Package
.Guids
, Package
.Ppis
, Package
.Protocols
, Package
.Pcds
)
3635 for Index
in range(len(BeChecked
)):
3636 for Item
in CheckList
[Index
]:
3637 if Item
in BeChecked
[Index
]:
3638 Packages
+= [Package
]
3643 VfrPcds
= self
._GetPcdsMaybeUsedByVfr
()
3644 for Pkg
in self
.PlatformInfo
.PackageList
:
3647 for VfrPcd
in VfrPcds
:
3648 if ((VfrPcd
.TokenCName
, VfrPcd
.TokenSpaceGuidCName
, 'DynamicEx') in Pkg
.Pcds
or
3649 (VfrPcd
.TokenCName
, VfrPcd
.TokenSpaceGuidCName
, 'Dynamic') in Pkg
.Pcds
):
3653 ModuleType
= self
.ModuleType
3654 if ModuleType
== 'UEFI_DRIVER' and self
.DepexGenerated
:
3655 ModuleType
= 'DXE_DRIVER'
3658 if self
.PcdIsDriver
!= '':
3659 DriverType
= self
.PcdIsDriver
3662 MDefs
= self
.Module
.Defines
3665 'module_name' : self
.Name
,
3666 'module_guid' : Guid
,
3667 'module_module_type' : ModuleType
,
3668 'module_version_string' : [MDefs
['VERSION_STRING']] if 'VERSION_STRING' in MDefs
else [],
3669 'pcd_is_driver_string' : [],
3670 'module_uefi_specification_version' : [],
3671 'module_pi_specification_version' : [],
3672 'module_entry_point' : self
.Module
.ModuleEntryPointList
,
3673 'module_unload_image' : self
.Module
.ModuleUnloadImageList
,
3674 'module_constructor' : self
.Module
.ConstructorList
,
3675 'module_destructor' : self
.Module
.DestructorList
,
3676 'module_shadow' : [MDefs
['SHADOW']] if 'SHADOW' in MDefs
else [],
3677 'module_pci_vendor_id' : [MDefs
['PCI_VENDOR_ID']] if 'PCI_VENDOR_ID' in MDefs
else [],
3678 'module_pci_device_id' : [MDefs
['PCI_DEVICE_ID']] if 'PCI_DEVICE_ID' in MDefs
else [],
3679 'module_pci_class_code' : [MDefs
['PCI_CLASS_CODE']] if 'PCI_CLASS_CODE' in MDefs
else [],
3680 'module_pci_revision' : [MDefs
['PCI_REVISION']] if 'PCI_REVISION' in MDefs
else [],
3681 'module_build_number' : [MDefs
['BUILD_NUMBER']] if 'BUILD_NUMBER' in MDefs
else [],
3682 'module_spec' : [MDefs
['SPEC']] if 'SPEC' in MDefs
else [],
3683 'module_uefi_hii_resource_section' : [MDefs
['UEFI_HII_RESOURCE_SECTION']] if 'UEFI_HII_RESOURCE_SECTION' in MDefs
else [],
3684 'module_uni_file' : [MDefs
['MODULE_UNI_FILE']] if 'MODULE_UNI_FILE' in MDefs
else [],
3685 'module_arch' : self
.Arch
,
3686 'package_item' : ['%s' % (Package
.MetaFile
.File
.replace('\\', '/')) for Package
in Packages
],
3688 'patchablepcd_item' : [],
3690 'protocol_item' : [],
3694 'libraryclasses_item' : []
3697 if self
.AutoGenVersion
> int(gInfSpecVersion
, 0):
3698 AsBuiltInfDict
['module_inf_version'] = '0x%08x' % self
.AutoGenVersion
3700 AsBuiltInfDict
['module_inf_version'] = gInfSpecVersion
3703 AsBuiltInfDict
['pcd_is_driver_string'] += [DriverType
]
3705 if 'UEFI_SPECIFICATION_VERSION' in self
.Specification
:
3706 AsBuiltInfDict
['module_uefi_specification_version'] += [self
.Specification
['UEFI_SPECIFICATION_VERSION']]
3707 if 'PI_SPECIFICATION_VERSION' in self
.Specification
:
3708 AsBuiltInfDict
['module_pi_specification_version'] += [self
.Specification
['PI_SPECIFICATION_VERSION']]
3710 OutputDir
= self
.OutputDir
.replace('\\', '/').strip('/')
3712 for Item
in self
.CodaTargetList
:
3713 File
= Item
.Target
.Path
.replace('\\', '/').strip('/').replace(OutputDir
, '').strip('/')
3714 if Item
.Target
.Ext
.lower() == '.aml':
3715 AsBuiltInfDict
['binary_item'] += ['ASL|' + File
]
3716 elif Item
.Target
.Ext
.lower() == '.acpi':
3717 AsBuiltInfDict
['binary_item'] += ['ACPI|' + File
]
3718 elif Item
.Target
.Ext
.lower() == '.efi':
3719 AsBuiltInfDict
['binary_item'] += ['PE32|' + self
.Name
+ '.efi']
3721 AsBuiltInfDict
['binary_item'] += ['BIN|' + File
]
3722 if self
.DepexGenerated
:
3723 if self
.ModuleType
in ['PEIM']:
3724 AsBuiltInfDict
['binary_item'] += ['PEI_DEPEX|' + self
.Name
+ '.depex']
3725 if self
.ModuleType
in ['DXE_DRIVER', 'DXE_RUNTIME_DRIVER', 'DXE_SAL_DRIVER', 'UEFI_DRIVER']:
3726 AsBuiltInfDict
['binary_item'] += ['DXE_DEPEX|' + self
.Name
+ '.depex']
3727 if self
.ModuleType
in ['DXE_SMM_DRIVER']:
3728 AsBuiltInfDict
['binary_item'] += ['SMM_DEPEX|' + self
.Name
+ '.depex']
3730 Bin
= self
._GenOffsetBin
()
3732 AsBuiltInfDict
['binary_item'] += ['BIN|%s' % Bin
]
3734 for Root
, Dirs
, Files
in os
.walk(OutputDir
):
3736 if File
.lower().endswith('.pdb'):
3737 AsBuiltInfDict
['binary_item'] += ['DISPOSABLE|' + File
]
3738 HeaderComments
= self
.Module
.HeaderComments
3740 for Index
in range(len(HeaderComments
)):
3741 if HeaderComments
[Index
].find('@BinaryHeader') != -1:
3742 HeaderComments
[Index
] = HeaderComments
[Index
].replace('@BinaryHeader', '@file')
3745 AsBuiltInfDict
['header_comments'] = '\n'.join(HeaderComments
[StartPos
:]).replace(':#', '://')
3746 AsBuiltInfDict
['tail_comments'] = '\n'.join(self
.Module
.TailComments
)
3749 (self
.ProtocolList
, self
._ProtocolComments
, 'protocol_item'),
3750 (self
.PpiList
, self
._PpiComments
, 'ppi_item'),
3751 (GuidList
, self
._GuidComments
, 'guid_item')
3753 for Item
in GenList
:
3754 for CName
in Item
[0]:
3756 if CName
in Item
[1]:
3757 Comments
= '\n '.join(Item
[1][CName
])
3760 Entry
= Comments
+ '\n ' + CName
3761 AsBuiltInfDict
[Item
[2]].append(Entry
)
3762 PatchList
= parsePcdInfoFromMapFile(
3763 os
.path
.join(self
.OutputDir
, self
.Name
+ '.map'),
3764 os
.path
.join(self
.OutputDir
, self
.Name
+ '.efi')
3767 for PatchPcd
in PatchList
:
3768 if PatchPcd
[0] in PatchablePcds
:
3770 elif PatchPcd
[0] + '_PatchableInModule' in PatchablePcds
:
3771 key
= PatchPcd
[0] + '_PatchableInModule'
3774 Pcd
= PatchablePcds
[key
]
3775 TokenCName
= PatchPcd
[0]
3777 if Pcd
.DatumType
!= 'VOID*':
3778 HexFormat
= '0x%02x'
3779 if Pcd
.DatumType
== 'UINT16':
3780 HexFormat
= '0x%04x'
3781 elif Pcd
.DatumType
== 'UINT32':
3782 HexFormat
= '0x%08x'
3783 elif Pcd
.DatumType
== 'UINT64':
3784 HexFormat
= '0x%016x'
3785 PcdValue
= HexFormat
% int(Pcd
.DefaultValue
, 0)
3787 if Pcd
.MaxDatumSize
== None or Pcd
.MaxDatumSize
== '':
3788 EdkLogger
.error("build", AUTOGEN_ERROR
,
3789 "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
3791 ArraySize
= int(Pcd
.MaxDatumSize
, 0)
3792 PcdValue
= Pcd
.DefaultValue
3793 if PcdValue
[0] != '{':
3795 if PcdValue
[0] == 'L':
3797 PcdValue
= PcdValue
.lstrip('L')
3798 PcdValue
= eval(PcdValue
)
3800 for Index
in range(0, len(PcdValue
)):
3802 CharVal
= ord(PcdValue
[Index
])
3803 NewValue
= NewValue
+ '0x%02x' % (CharVal
& 0x00FF) + ', ' \
3804 + '0x%02x' % (CharVal
>> 8) + ', '
3806 NewValue
= NewValue
+ '0x%02x' % (ord(PcdValue
[Index
]) % 0x100) + ', '
3809 Padding
= Padding
* 2
3810 ArraySize
= ArraySize
/ 2
3811 if ArraySize
< (len(PcdValue
) + 1):
3812 EdkLogger
.error("build", AUTOGEN_ERROR
,
3813 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
3815 if ArraySize
> len(PcdValue
) + 1:
3816 NewValue
= NewValue
+ Padding
* (ArraySize
- len(PcdValue
) - 1)
3817 PcdValue
= NewValue
+ Padding
.strip().rstrip(',') + '}'
3818 elif len(PcdValue
.split(',')) <= ArraySize
:
3819 PcdValue
= PcdValue
.rstrip('}') + ', 0x00' * (ArraySize
- len(PcdValue
.split(',')))
3822 EdkLogger
.error("build", AUTOGEN_ERROR
,
3823 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
3825 PcdItem
= '%s.%s|%s|0x%X' % \
3826 (Pcd
.TokenSpaceGuidCName
, TokenCName
, PcdValue
, PatchPcd
[1])
3828 if (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) in self
._PcdComments
:
3829 PcdComments
= '\n '.join(self
._PcdComments
[Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
])
3831 PcdItem
= PcdComments
+ '\n ' + PcdItem
3832 AsBuiltInfDict
['patchablepcd_item'].append(PcdItem
)
3835 for Pcd
in Pcds
+ VfrPcds
:
3840 TokenCName
= Pcd
.TokenCName
3841 for PcdItem
in GlobalData
.MixedPcd
:
3842 if (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
3843 TokenCName
= PcdItem
[0]
3845 if Pcd
.Type
== TAB_PCDS_DYNAMIC_EX_HII
:
3846 for SkuName
in Pcd
.SkuInfoList
:
3847 SkuInfo
= Pcd
.SkuInfoList
[SkuName
]
3848 SkuId
= SkuInfo
.SkuId
3849 HiiInfo
= '## %s|%s|%s' % (SkuInfo
.VariableName
, SkuInfo
.VariableGuid
, SkuInfo
.VariableOffset
)
3853 # Don't generate duplicated HII PCD
3855 if (SkuId
, Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) in HiiPcds
:
3858 HiiPcds
.append((SkuId
, Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
))
3859 if (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) in self
._PcdComments
:
3860 PcdCommentList
= self
._PcdComments
[Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
][:]
3864 for Index
, Comment
in enumerate(PcdCommentList
):
3865 for Usage
in UsageList
:
3866 if Comment
.find(Usage
) != -1:
3870 if UsageIndex
!= -1:
3871 PcdCommentList
[UsageIndex
] = '## %s %s %s' % (UsageStr
, HiiInfo
, PcdCommentList
[UsageIndex
].replace(UsageStr
, ''))
3873 PcdCommentList
.append('## UNDEFINED ' + HiiInfo
)
3874 PcdComments
= '\n '.join(PcdCommentList
)
3875 PcdEntry
= Pcd
.TokenSpaceGuidCName
+ '.' + TokenCName
3877 PcdEntry
= PcdComments
+ '\n ' + PcdEntry
3878 AsBuiltInfDict
['pcd_item'] += [PcdEntry
]
3879 for Item
in self
.BuildOption
:
3880 if 'FLAGS' in self
.BuildOption
[Item
]:
3881 AsBuiltInfDict
['flags_item'] += ['%s:%s_%s_%s_%s_FLAGS = %s' % (self
.ToolChainFamily
, self
.BuildTarget
, self
.ToolChain
, self
.Arch
, Item
, self
.BuildOption
[Item
]['FLAGS'].strip())]
3883 # Generated LibraryClasses section in comments.
3884 for Library
in self
.LibraryAutoGenList
:
3885 AsBuiltInfDict
['libraryclasses_item'] += [Library
.MetaFile
.File
.replace('\\', '/')]
3887 # Generated depex expression section in comments.
3888 AsBuiltInfDict
['depexsection_item'] = ''
3889 DepexExpresion
= self
._GetDepexExpresionString
()
3891 AsBuiltInfDict
['depexsection_item'] = DepexExpresion
3893 AsBuiltInf
= TemplateString()
3894 AsBuiltInf
.Append(gAsBuiltInfHeaderString
.Replace(AsBuiltInfDict
))
3896 SaveFileOnChange(os
.path
.join(self
.OutputDir
, self
.Name
+ '.inf'), str(AsBuiltInf
), False)
3898 self
.IsAsBuiltInfCreated
= True
3900 ## Create makefile for the module and its dependent libraries
3902 # @param CreateLibraryMakeFile Flag indicating if or not the makefiles of
3903 # dependent libraries will be created
3905 def CreateMakeFile(self
, CreateLibraryMakeFile
=True):
3906 # Ignore generating makefile when it is a binary module
3907 if self
.IsBinaryModule
:
3910 if self
.IsMakeFileCreated
:
3913 if not self
.IsLibrary
and CreateLibraryMakeFile
:
3914 for LibraryAutoGen
in self
.LibraryAutoGenList
:
3915 LibraryAutoGen
.CreateMakeFile()
3917 if len(self
.CustomMakefile
) == 0:
3918 Makefile
= GenMake
.ModuleMakefile(self
)
3920 Makefile
= GenMake
.CustomMakefile(self
)
3921 if Makefile
.Generate():
3922 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated makefile for module %s [%s]" %
3923 (self
.Name
, self
.Arch
))
3925 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Skipped the generation of makefile for module %s [%s]" %
3926 (self
.Name
, self
.Arch
))
3928 self
.IsMakeFileCreated
= True
3930 def CopyBinaryFiles(self
):
3931 for File
in self
.Module
.Binaries
:
3933 DstPath
= os
.path
.join(self
.OutputDir
, os
.path
.basename(SrcPath
))
3934 CopyLongFilePath(SrcPath
, DstPath
)
3935 ## Create autogen code for the module and its dependent libraries
3937 # @param CreateLibraryCodeFile Flag indicating if or not the code of
3938 # dependent libraries will be created
3940 def CreateCodeFile(self
, CreateLibraryCodeFile
=True):
3941 if self
.IsCodeFileCreated
:
3944 # Need to generate PcdDatabase even PcdDriver is binarymodule
3945 if self
.IsBinaryModule
and self
.PcdIsDriver
!= '':
3946 CreatePcdDatabaseCode(self
, TemplateString(), TemplateString())
3948 if self
.IsBinaryModule
:
3950 self
.CopyBinaryFiles()
3953 if not self
.IsLibrary
and CreateLibraryCodeFile
:
3954 for LibraryAutoGen
in self
.LibraryAutoGenList
:
3955 LibraryAutoGen
.CreateCodeFile()
3958 IgoredAutoGenList
= []
3960 for File
in self
.AutoGenFileList
:
3961 if GenC
.Generate(File
.Path
, self
.AutoGenFileList
[File
], File
.IsBinary
):
3962 #Ignore Edk AutoGen.c
3963 if self
.AutoGenVersion
< 0x00010005 and File
.Name
== 'AutoGen.c':
3966 AutoGenList
.append(str(File
))
3968 IgoredAutoGenList
.append(str(File
))
3970 # Skip the following code for EDK I inf
3971 if self
.AutoGenVersion
< 0x00010005:
3974 for ModuleType
in self
.DepexList
:
3975 # Ignore empty [depex] section or [depex] section for "USER_DEFINED" module
3976 if len(self
.DepexList
[ModuleType
]) == 0 or ModuleType
== "USER_DEFINED":
3979 Dpx
= GenDepex
.DependencyExpression(self
.DepexList
[ModuleType
], ModuleType
, True)
3980 DpxFile
= gAutoGenDepexFileName
% {"module_name" : self
.Name
}
3982 if len(Dpx
.PostfixNotation
) <> 0:
3983 self
.DepexGenerated
= True
3985 if Dpx
.Generate(path
.join(self
.OutputDir
, DpxFile
)):
3986 AutoGenList
.append(str(DpxFile
))
3988 IgoredAutoGenList
.append(str(DpxFile
))
3990 if IgoredAutoGenList
== []:
3991 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated [%s] files for module %s [%s]" %
3992 (" ".join(AutoGenList
), self
.Name
, self
.Arch
))
3993 elif AutoGenList
== []:
3994 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Skipped the generation of [%s] files for module %s [%s]" %
3995 (" ".join(IgoredAutoGenList
), self
.Name
, self
.Arch
))
3997 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated [%s] (skipped %s) files for module %s [%s]" %
3998 (" ".join(AutoGenList
), " ".join(IgoredAutoGenList
), self
.Name
, self
.Arch
))
4000 self
.IsCodeFileCreated
= True
4003 ## Summarize the ModuleAutoGen objects of all libraries used by this module
4004 def _GetLibraryAutoGenList(self
):
4005 if self
._LibraryAutoGenList
== None:
4006 self
._LibraryAutoGenList
= []
4007 for Library
in self
.DependentLibraryList
:
4014 self
.PlatformInfo
.MetaFile
4016 if La
not in self
._LibraryAutoGenList
:
4017 self
._LibraryAutoGenList
.append(La
)
4018 for Lib
in La
.CodaTargetList
:
4019 self
._ApplyBuildRule
(Lib
.Target
, TAB_UNKNOWN_FILE
)
4020 return self
._LibraryAutoGenList
4022 Module
= property(_GetModule
)
4023 Name
= property(_GetBaseName
)
4024 Guid
= property(_GetGuid
)
4025 Version
= property(_GetVersion
)
4026 ModuleType
= property(_GetModuleType
)
4027 ComponentType
= property(_GetComponentType
)
4028 BuildType
= property(_GetBuildType
)
4029 PcdIsDriver
= property(_GetPcdIsDriver
)
4030 AutoGenVersion
= property(_GetAutoGenVersion
)
4031 Macros
= property(_GetMacros
)
4032 Specification
= property(_GetSpecification
)
4034 IsLibrary
= property(_IsLibrary
)
4035 IsBinaryModule
= property(_IsBinaryModule
)
4036 BuildDir
= property(_GetBuildDir
)
4037 OutputDir
= property(_GetOutputDir
)
4038 DebugDir
= property(_GetDebugDir
)
4039 MakeFileDir
= property(_GetMakeFileDir
)
4040 CustomMakefile
= property(_GetCustomMakefile
)
4042 IncludePathList
= property(_GetIncludePathList
)
4043 IncludePathLength
= property(_GetIncludePathLength
)
4044 AutoGenFileList
= property(_GetAutoGenFileList
)
4045 UnicodeFileList
= property(_GetUnicodeFileList
)
4046 SourceFileList
= property(_GetSourceFileList
)
4047 BinaryFileList
= property(_GetBinaryFiles
) # FileType : [File List]
4048 Targets
= property(_GetTargets
)
4049 IntroTargetList
= property(_GetIntroTargetList
)
4050 CodaTargetList
= property(_GetFinalTargetList
)
4051 FileTypes
= property(_GetFileTypes
)
4052 BuildRules
= property(_GetBuildRules
)
4054 DependentPackageList
= property(_GetDependentPackageList
)
4055 DependentLibraryList
= property(_GetLibraryList
)
4056 LibraryAutoGenList
= property(_GetLibraryAutoGenList
)
4057 DerivedPackageList
= property(_GetDerivedPackageList
)
4059 ModulePcdList
= property(_GetModulePcdList
)
4060 LibraryPcdList
= property(_GetLibraryPcdList
)
4061 GuidList
= property(_GetGuidList
)
4062 ProtocolList
= property(_GetProtocolList
)
4063 PpiList
= property(_GetPpiList
)
4064 DepexList
= property(_GetDepexTokenList
)
4065 DxsFile
= property(_GetDxsFile
)
4066 DepexExpressionList
= property(_GetDepexExpressionTokenList
)
4067 BuildOption
= property(_GetModuleBuildOption
)
4068 BuildOptionIncPathList
= property(_GetBuildOptionIncPathList
)
4069 BuildCommand
= property(_GetBuildCommand
)
4071 FixedAtBuildPcds
= property(_GetFixedAtBuildPcds
)
4073 # This acts like the main() function for the script, unless it is 'import'ed into another script.
4074 if __name__
== '__main__':