2 # Generate AutoGen.h, AutoGen.c and *.depex files
4 # Copyright (c) 2007 - 2019, Intel Corporation. All rights reserved.<BR>
5 # Copyright (c) 2018, Hewlett Packard Enterprise Development, L.P.<BR>
6 # Copyright (c) 2019, American Megatrends, Inc. All rights reserved.<BR>
8 # This program and the accompanying materials
9 # are licensed and made available under the terms and conditions of the BSD License
10 # which accompanies this distribution. The full text of the license may be found at
11 # http://opensource.org/licenses/bsd-license.php
13 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
19 from __future__
import print_function
20 from __future__
import absolute_import
21 import Common
.LongFilePathOs
as os
23 import os
.path
as path
29 from . import GenDepex
30 from io
import BytesIO
32 from .StrGather
import *
33 from .BuildEngine
import BuildRule
35 from Common
.LongFilePathSupport
import CopyLongFilePath
36 from Common
.BuildToolError
import *
37 from Common
.DataType
import *
38 from Common
.Misc
import *
39 from Common
.StringUtils
import *
40 import Common
.GlobalData
as GlobalData
41 from GenFds
.FdfParser
import *
42 from CommonDataClass
.CommonClass
import SkuInfoClass
43 from GenPatchPcdTable
.GenPatchPcdTable
import parsePcdInfoFromMapFile
44 import Common
.VpdInfoFile
as VpdInfoFile
45 from .GenPcdDb
import CreatePcdDatabaseCode
46 from Workspace
.MetaFileCommentParser
import UsageList
47 from Workspace
.WorkspaceCommon
import GetModuleLibInstances
48 from Common
.MultipleWorkspace
import MultipleWorkspace
as mws
49 from . import InfSectionParser
52 from .GenVar
import VariableMgr
, var_info
53 from collections
import OrderedDict
54 from collections
import defaultdict
55 from Workspace
.WorkspaceCommon
import OrderedListDict
56 from Common
.ToolDefClassObject
import gDefaultToolsDefFile
58 from Common
.caching
import cached_property
, cached_class_function
60 ## Regular expression for splitting Dependency Expression string into tokens
61 gDepexTokenPattern
= re
.compile("(\(|\)|\w+| \S+\.inf)")
63 ## Regular expression for match: PCD(xxxx.yyy)
64 gPCDAsGuidPattern
= re
.compile(r
"^PCD\(.+\..+\)$")
67 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT
68 # is the former use /I , the Latter used -I to specify include directories
70 gBuildOptIncludePatternMsft
= re
.compile(r
"(?:.*?)/I[ \t]*([^ ]*)", re
.MULTILINE | re
.DOTALL
)
71 gBuildOptIncludePatternOther
= re
.compile(r
"(?:.*?)-I[ \t]*([^ ]*)", re
.MULTILINE | re
.DOTALL
)
74 # Match name = variable
76 gEfiVarStoreNamePattern
= re
.compile("\s*name\s*=\s*(\w+)")
78 # The format of guid in efivarstore statement likes following and must be correct:
79 # guid = {0xA04A27f4, 0xDF00, 0x4D42, {0xB5, 0x52, 0x39, 0x51, 0x13, 0x02, 0x11, 0x3D}}
81 gEfiVarStoreGuidPattern
= re
.compile("\s*guid\s*=\s*({.*?{.*?}\s*})")
83 ## Mapping Makefile type
84 gMakeTypeMap
= {TAB_COMPILER_MSFT
:"nmake", "GCC":"gmake"}
87 ## Build rule configuration file
88 gDefaultBuildRuleFile
= 'build_rule.txt'
90 ## Build rule default version
91 AutoGenReqBuildRuleVerNum
= "0.1"
93 ## default file name for AutoGen
94 gAutoGenCodeFileName
= "AutoGen.c"
95 gAutoGenHeaderFileName
= "AutoGen.h"
96 gAutoGenStringFileName
= "%(module_name)sStrDefs.h"
97 gAutoGenStringFormFileName
= "%(module_name)sStrDefs.hpk"
98 gAutoGenDepexFileName
= "%(module_name)s.depex"
99 gAutoGenImageDefFileName
= "%(module_name)sImgDefs.h"
100 gAutoGenIdfFileName
= "%(module_name)sIdf.hpk"
101 gInfSpecVersion
= "0x00010017"
104 # Template string to generic AsBuilt INF
106 gAsBuiltInfHeaderString
= TemplateString("""${header_comments}
109 # FILE auto-generated
112 INF_VERSION = ${module_inf_version}
113 BASE_NAME = ${module_name}
114 FILE_GUID = ${module_guid}
115 MODULE_TYPE = ${module_module_type}${BEGIN}
116 VERSION_STRING = ${module_version_string}${END}${BEGIN}
117 PCD_IS_DRIVER = ${pcd_is_driver_string}${END}${BEGIN}
118 UEFI_SPECIFICATION_VERSION = ${module_uefi_specification_version}${END}${BEGIN}
119 PI_SPECIFICATION_VERSION = ${module_pi_specification_version}${END}${BEGIN}
120 ENTRY_POINT = ${module_entry_point}${END}${BEGIN}
121 UNLOAD_IMAGE = ${module_unload_image}${END}${BEGIN}
122 CONSTRUCTOR = ${module_constructor}${END}${BEGIN}
123 DESTRUCTOR = ${module_destructor}${END}${BEGIN}
124 SHADOW = ${module_shadow}${END}${BEGIN}
125 PCI_VENDOR_ID = ${module_pci_vendor_id}${END}${BEGIN}
126 PCI_DEVICE_ID = ${module_pci_device_id}${END}${BEGIN}
127 PCI_CLASS_CODE = ${module_pci_class_code}${END}${BEGIN}
128 PCI_REVISION = ${module_pci_revision}${END}${BEGIN}
129 BUILD_NUMBER = ${module_build_number}${END}${BEGIN}
130 SPEC = ${module_spec}${END}${BEGIN}
131 UEFI_HII_RESOURCE_SECTION = ${module_uefi_hii_resource_section}${END}${BEGIN}
132 MODULE_UNI_FILE = ${module_uni_file}${END}
134 [Packages.${module_arch}]${BEGIN}
135 ${package_item}${END}
137 [Binaries.${module_arch}]${BEGIN}
140 [PatchPcd.${module_arch}]${BEGIN}
144 [Protocols.${module_arch}]${BEGIN}
148 [Ppis.${module_arch}]${BEGIN}
152 [Guids.${module_arch}]${BEGIN}
156 [PcdEx.${module_arch}]${BEGIN}
160 [LibraryClasses.${module_arch}]
161 ## @LIB_INSTANCES${BEGIN}
162 # ${libraryclasses_item}${END}
166 ${userextension_tianocore_item}
170 [BuildOptions.${module_arch}]
172 ## ${flags_item}${END}
174 ## Split command line option string to list
176 # subprocess.Popen needs the args to be a sequence. Otherwise there's problem
177 # in non-windows platform to launch command
179 def _SplitOption(OptionString
):
184 for Index
in range(0, len(OptionString
)):
185 CurrentChar
= OptionString
[Index
]
186 if CurrentChar
in ['"', "'"]:
187 if QuotationMark
== CurrentChar
:
189 elif QuotationMark
== "":
190 QuotationMark
= CurrentChar
195 if CurrentChar
in ["/", "-"] and LastChar
in [" ", "\t", "\r", "\n"]:
196 if Index
> OptionStart
:
197 OptionList
.append(OptionString
[OptionStart
:Index
- 1])
199 LastChar
= CurrentChar
200 OptionList
.append(OptionString
[OptionStart
:])
204 # Convert string to C format array
206 def _ConvertStringToByteArray(Value
):
207 Value
= Value
.strip()
211 if not Value
.endswith('}'):
213 Value
= Value
.replace(' ', '').replace('{', '').replace('}', '')
214 ValFields
= Value
.split(',')
216 for Index
in range(len(ValFields
)):
217 ValFields
[Index
] = str(int(ValFields
[Index
], 0))
220 Value
= '{' + ','.join(ValFields
) + '}'
224 if Value
.startswith('L"'):
225 if not Value
.endswith('"'):
229 elif not Value
.startswith('"') or not Value
.endswith('"'):
232 Value
= eval(Value
) # translate escape character
234 for Index
in range(0, len(Value
)):
236 NewValue
= NewValue
+ str(ord(Value
[Index
]) % 0x10000) + ','
238 NewValue
= NewValue
+ str(ord(Value
[Index
]) % 0x100) + ','
239 Value
= NewValue
+ '0}'
242 ## Base class for AutoGen
244 # This class just implements the cache mechanism of AutoGen objects.
246 class AutoGen(object):
247 # database to maintain the objects in each child class
248 __ObjectCache
= {} # (BuildTarget, ToolChain, ARCH, platform file): AutoGen object
252 # @param Class class object of real AutoGen class
253 # (WorkspaceAutoGen, ModuleAutoGen or PlatformAutoGen)
254 # @param Workspace Workspace directory or WorkspaceAutoGen object
255 # @param MetaFile The path of meta file
256 # @param Target Build target
257 # @param Toolchain Tool chain name
258 # @param Arch Target arch
259 # @param *args The specific class related parameters
260 # @param **kwargs The specific class related dict parameters
262 def __new__(cls
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
263 # check if the object has been created
264 Key
= (Target
, Toolchain
, Arch
, MetaFile
)
265 if Key
in cls
.__ObjectCache
:
266 # if it exists, just return it directly
267 return cls
.__ObjectCache
[Key
]
268 # it didnt exist. create it, cache it, then return it
269 RetVal
= cls
.__ObjectCache
[Key
] = super(AutoGen
, cls
).__new
__(cls
)
275 # The file path of platform file will be used to represent hash value of this object
277 # @retval int Hash value of the file path of platform file
280 return hash(self
.MetaFile
)
284 # The file path of platform file will be used to represent this object
286 # @retval string String of platform file path
289 return str(self
.MetaFile
)
292 def __eq__(self
, Other
):
293 return Other
and self
.MetaFile
== Other
295 ## Workspace AutoGen class
297 # This class is used mainly to control the whole platform build for different
298 # architecture. This class will generate top level makefile.
300 class WorkspaceAutoGen(AutoGen
):
301 # call super().__init__ then call the worker function with different parameter count
302 def __init__(self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
303 if not hasattr(self
, "_Init"):
304 self
._InitWorker
(Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
)
307 ## Initialize WorkspaceAutoGen
309 # @param WorkspaceDir Root directory of workspace
310 # @param ActivePlatform Meta-file of active platform
311 # @param Target Build target
312 # @param Toolchain Tool chain name
313 # @param ArchList List of architecture of current build
314 # @param MetaFileDb Database containing meta-files
315 # @param BuildConfig Configuration of build
316 # @param ToolDefinition Tool chain definitions
317 # @param FlashDefinitionFile File of flash definition
318 # @param Fds FD list to be generated
319 # @param Fvs FV list to be generated
320 # @param Caps Capsule list to be generated
321 # @param SkuId SKU id from command line
323 def _InitWorker(self
, WorkspaceDir
, ActivePlatform
, Target
, Toolchain
, ArchList
, MetaFileDb
,
324 BuildConfig
, ToolDefinition
, FlashDefinitionFile
='', Fds
=None, Fvs
=None, Caps
=None, SkuId
='', UniFlag
=None,
325 Progress
=None, BuildModule
=None):
326 self
.BuildDatabase
= MetaFileDb
327 self
.MetaFile
= ActivePlatform
328 self
.WorkspaceDir
= WorkspaceDir
329 self
.Platform
= self
.BuildDatabase
[self
.MetaFile
, TAB_ARCH_COMMON
, Target
, Toolchain
]
330 GlobalData
.gActivePlatform
= self
.Platform
331 self
.BuildTarget
= Target
332 self
.ToolChain
= Toolchain
333 self
.ArchList
= ArchList
335 self
.UniFlag
= UniFlag
337 self
.TargetTxt
= BuildConfig
338 self
.ToolDef
= ToolDefinition
339 self
.FdfFile
= FlashDefinitionFile
340 self
.FdTargetList
= Fds
if Fds
else []
341 self
.FvTargetList
= Fvs
if Fvs
else []
342 self
.CapTargetList
= Caps
if Caps
else []
343 self
.AutoGenObjectList
= []
346 # there's many relative directory operations, so ...
347 os
.chdir(self
.WorkspaceDir
)
352 if not self
.ArchList
:
353 ArchList
= set(self
.Platform
.SupArchList
)
355 ArchList
= set(self
.ArchList
) & set(self
.Platform
.SupArchList
)
357 EdkLogger
.error("build", PARAMETER_INVALID
,
358 ExtraData
= "Invalid ARCH specified. [Valid ARCH: %s]" % (" ".join(self
.Platform
.SupArchList
)))
359 elif self
.ArchList
and len(ArchList
) != len(self
.ArchList
):
360 SkippedArchList
= set(self
.ArchList
).symmetric_difference(set(self
.Platform
.SupArchList
))
361 EdkLogger
.verbose("\nArch [%s] is ignored because the platform supports [%s] only!"
362 % (" ".join(SkippedArchList
), " ".join(self
.Platform
.SupArchList
)))
363 self
.ArchList
= tuple(ArchList
)
365 # Validate build target
366 if self
.BuildTarget
not in self
.Platform
.BuildTargets
:
367 EdkLogger
.error("build", PARAMETER_INVALID
,
368 ExtraData
="Build target [%s] is not supported by the platform. [Valid target: %s]"
369 % (self
.BuildTarget
, " ".join(self
.Platform
.BuildTargets
)))
372 # parse FDF file to get PCDs in it, if any
374 self
.FdfFile
= self
.Platform
.FlashDefinition
378 EdkLogger
.info('%-16s = %s' % ("Architecture(s)", ' '.join(self
.ArchList
)))
379 EdkLogger
.info('%-16s = %s' % ("Build target", self
.BuildTarget
))
380 EdkLogger
.info('%-16s = %s' % ("Toolchain", self
.ToolChain
))
382 EdkLogger
.info('\n%-24s = %s' % ("Active Platform", self
.Platform
))
384 EdkLogger
.info('%-24s = %s' % ("Active Module", BuildModule
))
387 EdkLogger
.info('%-24s = %s' % ("Flash Image Definition", self
.FdfFile
))
389 EdkLogger
.verbose("\nFLASH_DEFINITION = %s" % self
.FdfFile
)
392 Progress
.Start("\nProcessing meta-data")
396 # Mark now build in AutoGen Phase
398 GlobalData
.gAutoGenPhase
= True
399 Fdf
= FdfParser(self
.FdfFile
.Path
)
401 GlobalData
.gFdfParser
= Fdf
402 GlobalData
.gAutoGenPhase
= False
403 PcdSet
= Fdf
.Profile
.PcdDict
404 if Fdf
.CurrentFdName
and Fdf
.CurrentFdName
in Fdf
.Profile
.FdDict
:
405 FdDict
= Fdf
.Profile
.FdDict
[Fdf
.CurrentFdName
]
406 for FdRegion
in FdDict
.RegionList
:
407 if str(FdRegion
.RegionType
) is 'FILE' and self
.Platform
.VpdToolGuid
in str(FdRegion
.RegionDataList
):
408 if int(FdRegion
.Offset
) % 8 != 0:
409 EdkLogger
.error("build", FORMAT_INVALID
, 'The VPD Base Address %s must be 8-byte aligned.' % (FdRegion
.Offset
))
410 ModuleList
= Fdf
.Profile
.InfList
411 self
.FdfProfile
= Fdf
.Profile
412 for fvname
in self
.FvTargetList
:
413 if fvname
.upper() not in self
.FdfProfile
.FvDict
:
414 EdkLogger
.error("build", OPTION_VALUE_INVALID
,
415 "No such an FV in FDF file: %s" % fvname
)
417 # In DSC file may use FILE_GUID to override the module, then in the Platform.Modules use FILE_GUIDmodule.inf as key,
418 # but the path (self.MetaFile.Path) is the real path
419 for key
in self
.FdfProfile
.InfDict
:
421 MetaFile_cache
= defaultdict(set)
422 for Arch
in self
.ArchList
:
423 Current_Platform_cache
= self
.BuildDatabase
[self
.MetaFile
, Arch
, Target
, Toolchain
]
424 for Pkey
in Current_Platform_cache
.Modules
:
425 MetaFile_cache
[Arch
].add(Current_Platform_cache
.Modules
[Pkey
].MetaFile
)
426 for Inf
in self
.FdfProfile
.InfDict
[key
]:
427 ModuleFile
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, Arch
)
428 for Arch
in self
.ArchList
:
429 if ModuleFile
in MetaFile_cache
[Arch
]:
432 ModuleData
= self
.BuildDatabase
[ModuleFile
, Arch
, Target
, Toolchain
]
433 if not ModuleData
.IsBinaryModule
:
434 EdkLogger
.error('build', PARSER_ERROR
, "Module %s NOT found in DSC file; Is it really a binary module?" % ModuleFile
)
437 for Arch
in self
.ArchList
:
439 Platform
= self
.BuildDatabase
[self
.MetaFile
, Arch
, Target
, Toolchain
]
441 for Pkey
in Platform
.Modules
:
442 MetaFileList
.add(Platform
.Modules
[Pkey
].MetaFile
)
443 for Inf
in self
.FdfProfile
.InfDict
[key
]:
444 ModuleFile
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, Arch
)
445 if ModuleFile
in MetaFileList
:
447 ModuleData
= self
.BuildDatabase
[ModuleFile
, Arch
, Target
, Toolchain
]
448 if not ModuleData
.IsBinaryModule
:
449 EdkLogger
.error('build', PARSER_ERROR
, "Module %s NOT found in DSC file; Is it really a binary module?" % ModuleFile
)
454 self
.FdfProfile
= None
455 if self
.FdTargetList
:
456 EdkLogger
.info("No flash definition file found. FD [%s] will be ignored." % " ".join(self
.FdTargetList
))
457 self
.FdTargetList
= []
458 if self
.FvTargetList
:
459 EdkLogger
.info("No flash definition file found. FV [%s] will be ignored." % " ".join(self
.FvTargetList
))
460 self
.FvTargetList
= []
461 if self
.CapTargetList
:
462 EdkLogger
.info("No flash definition file found. Capsule [%s] will be ignored." % " ".join(self
.CapTargetList
))
463 self
.CapTargetList
= []
465 # apply SKU and inject PCDs from Flash Definition file
466 for Arch
in self
.ArchList
:
467 Platform
= self
.BuildDatabase
[self
.MetaFile
, Arch
, Target
, Toolchain
]
468 PlatformPcds
= Platform
.Pcds
469 self
._GuidDict
= Platform
._GuidDict
470 SourcePcdDict
= {TAB_PCDS_DYNAMIC_EX
:set(), TAB_PCDS_PATCHABLE_IN_MODULE
:set(),TAB_PCDS_DYNAMIC
:set(),TAB_PCDS_FIXED_AT_BUILD
:set()}
471 BinaryPcdDict
= {TAB_PCDS_DYNAMIC_EX
:set(), TAB_PCDS_PATCHABLE_IN_MODULE
:set()}
472 SourcePcdDict_Keys
= SourcePcdDict
.keys()
473 BinaryPcdDict_Keys
= BinaryPcdDict
.keys()
475 # generate the SourcePcdDict and BinaryPcdDict
476 PGen
= PlatformAutoGen(self
, self
.MetaFile
, Target
, Toolchain
, Arch
)
477 for BuildData
in PGen
.BuildDatabase
._CACHE
_.values():
478 if BuildData
.Arch
!= Arch
:
480 if BuildData
.MetaFile
.Ext
== '.inf':
481 for key
in BuildData
.Pcds
:
482 if BuildData
.Pcds
[key
].Pending
:
483 if key
in Platform
.Pcds
:
484 PcdInPlatform
= Platform
.Pcds
[key
]
485 if PcdInPlatform
.Type
:
486 BuildData
.Pcds
[key
].Type
= PcdInPlatform
.Type
487 BuildData
.Pcds
[key
].Pending
= False
489 if BuildData
.MetaFile
in Platform
.Modules
:
490 PlatformModule
= Platform
.Modules
[str(BuildData
.MetaFile
)]
491 if key
in PlatformModule
.Pcds
:
492 PcdInPlatform
= PlatformModule
.Pcds
[key
]
493 if PcdInPlatform
.Type
:
494 BuildData
.Pcds
[key
].Type
= PcdInPlatform
.Type
495 BuildData
.Pcds
[key
].Pending
= False
497 #Pcd used in Library, Pcd Type from reference module if Pcd Type is Pending
498 if BuildData
.Pcds
[key
].Pending
:
499 MGen
= ModuleAutoGen(self
, BuildData
.MetaFile
, Target
, Toolchain
, Arch
, self
.MetaFile
)
500 if MGen
and MGen
.IsLibrary
:
501 if MGen
in PGen
.LibraryAutoGenList
:
502 ReferenceModules
= MGen
.ReferenceModules
503 for ReferenceModule
in ReferenceModules
:
504 if ReferenceModule
.MetaFile
in Platform
.Modules
:
505 RefPlatformModule
= Platform
.Modules
[str(ReferenceModule
.MetaFile
)]
506 if key
in RefPlatformModule
.Pcds
:
507 PcdInReferenceModule
= RefPlatformModule
.Pcds
[key
]
508 if PcdInReferenceModule
.Type
:
509 BuildData
.Pcds
[key
].Type
= PcdInReferenceModule
.Type
510 BuildData
.Pcds
[key
].Pending
= False
513 if TAB_PCDS_DYNAMIC_EX
in BuildData
.Pcds
[key
].Type
:
514 if BuildData
.IsBinaryModule
:
515 BinaryPcdDict
[TAB_PCDS_DYNAMIC_EX
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
517 SourcePcdDict
[TAB_PCDS_DYNAMIC_EX
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
519 elif TAB_PCDS_PATCHABLE_IN_MODULE
in BuildData
.Pcds
[key
].Type
:
520 if BuildData
.MetaFile
.Ext
== '.inf':
521 if BuildData
.IsBinaryModule
:
522 BinaryPcdDict
[TAB_PCDS_PATCHABLE_IN_MODULE
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
524 SourcePcdDict
[TAB_PCDS_PATCHABLE_IN_MODULE
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
526 elif TAB_PCDS_DYNAMIC
in BuildData
.Pcds
[key
].Type
:
527 SourcePcdDict
[TAB_PCDS_DYNAMIC
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
528 elif TAB_PCDS_FIXED_AT_BUILD
in BuildData
.Pcds
[key
].Type
:
529 SourcePcdDict
[TAB_PCDS_FIXED_AT_BUILD
].add((BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
))
533 # A PCD can only use one type for all source modules
535 for i
in SourcePcdDict_Keys
:
536 for j
in SourcePcdDict_Keys
:
538 Intersections
= SourcePcdDict
[i
].intersection(SourcePcdDict
[j
])
539 if len(Intersections
) > 0:
543 "Building modules from source INFs, following PCD use %s and %s access method. It must be corrected to use only one access method." % (i
, j
),
544 ExtraData
='\n\t'.join(str(P
[1]+'.'+P
[0]) for P
in Intersections
)
548 # intersection the BinaryPCD for Mixed PCD
550 for i
in BinaryPcdDict_Keys
:
551 for j
in BinaryPcdDict_Keys
:
553 Intersections
= BinaryPcdDict
[i
].intersection(BinaryPcdDict
[j
])
554 for item
in Intersections
:
555 NewPcd1
= (item
[0] + '_' + i
, item
[1])
556 NewPcd2
= (item
[0] + '_' + j
, item
[1])
557 if item
not in GlobalData
.MixedPcd
:
558 GlobalData
.MixedPcd
[item
] = [NewPcd1
, NewPcd2
]
560 if NewPcd1
not in GlobalData
.MixedPcd
[item
]:
561 GlobalData
.MixedPcd
[item
].append(NewPcd1
)
562 if NewPcd2
not in GlobalData
.MixedPcd
[item
]:
563 GlobalData
.MixedPcd
[item
].append(NewPcd2
)
566 # intersection the SourcePCD and BinaryPCD for Mixed PCD
568 for i
in SourcePcdDict_Keys
:
569 for j
in BinaryPcdDict_Keys
:
571 Intersections
= SourcePcdDict
[i
].intersection(BinaryPcdDict
[j
])
572 for item
in Intersections
:
573 NewPcd1
= (item
[0] + '_' + i
, item
[1])
574 NewPcd2
= (item
[0] + '_' + j
, item
[1])
575 if item
not in GlobalData
.MixedPcd
:
576 GlobalData
.MixedPcd
[item
] = [NewPcd1
, NewPcd2
]
578 if NewPcd1
not in GlobalData
.MixedPcd
[item
]:
579 GlobalData
.MixedPcd
[item
].append(NewPcd1
)
580 if NewPcd2
not in GlobalData
.MixedPcd
[item
]:
581 GlobalData
.MixedPcd
[item
].append(NewPcd2
)
583 for BuildData
in PGen
.BuildDatabase
._CACHE
_.values():
584 if BuildData
.Arch
!= Arch
:
586 for key
in BuildData
.Pcds
:
587 for SinglePcd
in GlobalData
.MixedPcd
:
588 if (BuildData
.Pcds
[key
].TokenCName
, BuildData
.Pcds
[key
].TokenSpaceGuidCName
) == SinglePcd
:
589 for item
in GlobalData
.MixedPcd
[SinglePcd
]:
590 Pcd_Type
= item
[0].split('_')[-1]
591 if (Pcd_Type
== BuildData
.Pcds
[key
].Type
) or (Pcd_Type
== TAB_PCDS_DYNAMIC_EX
and BuildData
.Pcds
[key
].Type
in PCD_DYNAMIC_EX_TYPE_SET
) or \
592 (Pcd_Type
== TAB_PCDS_DYNAMIC
and BuildData
.Pcds
[key
].Type
in PCD_DYNAMIC_TYPE_SET
):
593 Value
= BuildData
.Pcds
[key
]
594 Value
.TokenCName
= BuildData
.Pcds
[key
].TokenCName
+ '_' + Pcd_Type
596 newkey
= (Value
.TokenCName
, key
[1])
598 newkey
= (Value
.TokenCName
, key
[1], key
[2])
599 del BuildData
.Pcds
[key
]
600 BuildData
.Pcds
[newkey
] = Value
604 # handle the mixed pcd in FDF file
606 if key
in GlobalData
.MixedPcd
:
609 for item
in GlobalData
.MixedPcd
[key
]:
612 #Collect package set information from INF of FDF
614 for Inf
in ModuleList
:
615 ModuleFile
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, Arch
)
616 if ModuleFile
in Platform
.Modules
:
618 ModuleData
= self
.BuildDatabase
[ModuleFile
, Arch
, Target
, Toolchain
]
619 PkgSet
.update(ModuleData
.Packages
)
620 Pkgs
= list(PkgSet
) + list(PGen
.PackageList
)
625 DecPcds
.add((Pcd
[0], Pcd
[1]))
626 DecPcdsKey
.add((Pcd
[0], Pcd
[1], Pcd
[2]))
628 Platform
.SkuName
= self
.SkuId
629 for Name
, Guid
,Fileds
in PcdSet
:
630 if (Name
, Guid
) not in DecPcds
:
634 "PCD (%s.%s) used in FDF is not declared in DEC files." % (Guid
, Name
),
635 File
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
, Fileds
][0],
636 Line
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
, Fileds
][1]
639 # Check whether Dynamic or DynamicEx PCD used in FDF file. If used, build break and give a error message.
640 if (Name
, Guid
, TAB_PCDS_FIXED_AT_BUILD
) in DecPcdsKey \
641 or (Name
, Guid
, TAB_PCDS_PATCHABLE_IN_MODULE
) in DecPcdsKey \
642 or (Name
, Guid
, TAB_PCDS_FEATURE_FLAG
) in DecPcdsKey
:
644 elif (Name
, Guid
, TAB_PCDS_DYNAMIC
) in DecPcdsKey
or (Name
, Guid
, TAB_PCDS_DYNAMIC_EX
) in DecPcdsKey
:
648 "Using Dynamic or DynamicEx type of PCD [%s.%s] in FDF file is not allowed." % (Guid
, Name
),
649 File
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
, Fileds
][0],
650 Line
= self
.FdfProfile
.PcdFileLineDict
[Name
, Guid
, Fileds
][1]
653 Pa
= PlatformAutoGen(self
, self
.MetaFile
, Target
, Toolchain
, Arch
)
655 # Explicitly collect platform's dynamic PCDs
657 Pa
.CollectPlatformDynamicPcds()
658 Pa
.CollectFixedAtBuildPcds()
659 self
.AutoGenObjectList
.append(Pa
)
662 # Generate Package level hash value
664 GlobalData
.gPackageHash
[Arch
] = {}
665 if GlobalData
.gUseHashCache
:
667 self
._GenPkgLevelHash
(Pkg
)
670 # Check PCDs token value conflict in each DEC file.
672 self
._CheckAllPcdsTokenValueConflict
()
675 # Check PCD type and definition between DSC and DEC
677 self
._CheckPcdDefineAndType
()
680 # Create BuildOptions Macro & PCD metafile, also add the Active Platform and FDF file.
682 content
= 'gCommandLineDefines: '
683 content
+= str(GlobalData
.gCommandLineDefines
)
684 content
+= TAB_LINE_BREAK
685 content
+= 'BuildOptionPcd: '
686 content
+= str(GlobalData
.BuildOptionPcd
)
687 content
+= TAB_LINE_BREAK
688 content
+= 'Active Platform: '
689 content
+= str(self
.Platform
)
690 content
+= TAB_LINE_BREAK
692 content
+= 'Flash Image Definition: '
693 content
+= str(self
.FdfFile
)
694 content
+= TAB_LINE_BREAK
695 SaveFileOnChange(os
.path
.join(self
.BuildDir
, 'BuildOptions'), content
, False)
698 # Create PcdToken Number file for Dynamic/DynamicEx Pcd.
700 PcdTokenNumber
= 'PcdTokenNumber: '
701 if Pa
.PcdTokenNumber
:
702 if Pa
.DynamicPcdList
:
703 for Pcd
in Pa
.DynamicPcdList
:
704 PcdTokenNumber
+= TAB_LINE_BREAK
705 PcdTokenNumber
+= str((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
))
706 PcdTokenNumber
+= ' : '
707 PcdTokenNumber
+= str(Pa
.PcdTokenNumber
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
])
708 SaveFileOnChange(os
.path
.join(self
.BuildDir
, 'PcdTokenNumber'), PcdTokenNumber
, False)
711 # Get set of workspace metafiles
713 AllWorkSpaceMetaFiles
= self
._GetMetaFiles
(Target
, Toolchain
, Arch
)
716 # Retrieve latest modified time of all metafiles
719 for f
in AllWorkSpaceMetaFiles
:
720 if os
.stat(f
)[8] > SrcTimeStamp
:
721 SrcTimeStamp
= os
.stat(f
)[8]
722 self
._SrcTimeStamp
= SrcTimeStamp
724 if GlobalData
.gUseHashCache
:
726 for files
in AllWorkSpaceMetaFiles
:
727 if files
.endswith('.dec'):
733 SaveFileOnChange(os
.path
.join(self
.BuildDir
, 'AutoGen.hash'), m
.hexdigest(), True)
734 GlobalData
.gPlatformHash
= m
.hexdigest()
737 # Write metafile list to build directory
739 AutoGenFilePath
= os
.path
.join(self
.BuildDir
, 'AutoGen')
740 if os
.path
.exists (AutoGenFilePath
):
741 os
.remove(AutoGenFilePath
)
742 if not os
.path
.exists(self
.BuildDir
):
743 os
.makedirs(self
.BuildDir
)
744 with
open(os
.path
.join(self
.BuildDir
, 'AutoGen'), 'w+') as file:
745 for f
in AllWorkSpaceMetaFiles
:
749 def _GenPkgLevelHash(self
, Pkg
):
750 if Pkg
.PackageName
in GlobalData
.gPackageHash
[Pkg
.Arch
]:
753 PkgDir
= os
.path
.join(self
.BuildDir
, Pkg
.Arch
, Pkg
.PackageName
)
754 CreateDirectory(PkgDir
)
755 HashFile
= os
.path
.join(PkgDir
, Pkg
.PackageName
+ '.hash')
757 # Get .dec file's hash value
758 f
= open(Pkg
.MetaFile
.Path
, 'r')
762 # Get include files hash value
764 for inc
in sorted(Pkg
.Includes
, key
=lambda x
: str(x
)):
765 for Root
, Dirs
, Files
in os
.walk(str(inc
)):
766 for File
in sorted(Files
):
767 File_Path
= os
.path
.join(Root
, File
)
768 f
= open(File_Path
, 'r')
772 SaveFileOnChange(HashFile
, m
.hexdigest(), True)
773 GlobalData
.gPackageHash
[Pkg
.Arch
][Pkg
.PackageName
] = m
.hexdigest()
775 def _GetMetaFiles(self
, Target
, Toolchain
, Arch
):
776 AllWorkSpaceMetaFiles
= set()
781 AllWorkSpaceMetaFiles
.add (self
.FdfFile
.Path
)
782 for f
in GlobalData
.gFdfParser
.GetAllIncludedFile():
783 AllWorkSpaceMetaFiles
.add (f
.FileName
)
787 AllWorkSpaceMetaFiles
.add(self
.MetaFile
.Path
)
790 # add build_rule.txt & tools_def.txt
792 AllWorkSpaceMetaFiles
.add(os
.path
.join(GlobalData
.gConfDirectory
, gDefaultBuildRuleFile
))
793 AllWorkSpaceMetaFiles
.add(os
.path
.join(GlobalData
.gConfDirectory
, gDefaultToolsDefFile
))
795 # add BuildOption metafile
797 AllWorkSpaceMetaFiles
.add(os
.path
.join(self
.BuildDir
, 'BuildOptions'))
799 # add PcdToken Number file for Dynamic/DynamicEx Pcd
801 AllWorkSpaceMetaFiles
.add(os
.path
.join(self
.BuildDir
, 'PcdTokenNumber'))
803 for Arch
in self
.ArchList
:
807 for Package
in PlatformAutoGen(self
, self
.MetaFile
, Target
, Toolchain
, Arch
).PackageList
:
808 AllWorkSpaceMetaFiles
.add(Package
.MetaFile
.Path
)
813 for filePath
in self
.BuildDatabase
[self
.MetaFile
, Arch
, Target
, Toolchain
]._RawData
.IncludedFiles
:
814 AllWorkSpaceMetaFiles
.add(filePath
.Path
)
816 return AllWorkSpaceMetaFiles
818 def _CheckPcdDefineAndType(self
):
819 PcdTypeSet
= {TAB_PCDS_FIXED_AT_BUILD
,
820 TAB_PCDS_PATCHABLE_IN_MODULE
,
821 TAB_PCDS_FEATURE_FLAG
,
825 # This dict store PCDs which are not used by any modules with specified arches
826 UnusedPcd
= OrderedDict()
827 for Pa
in self
.AutoGenObjectList
:
828 # Key of DSC's Pcds dictionary is PcdCName, TokenSpaceGuid
829 for Pcd
in Pa
.Platform
.Pcds
:
830 PcdType
= Pa
.Platform
.Pcds
[Pcd
].Type
832 # If no PCD type, this PCD comes from FDF
836 # Try to remove Hii and Vpd suffix
837 if PcdType
.startswith(TAB_PCDS_DYNAMIC_EX
):
838 PcdType
= TAB_PCDS_DYNAMIC_EX
839 elif PcdType
.startswith(TAB_PCDS_DYNAMIC
):
840 PcdType
= TAB_PCDS_DYNAMIC
842 for Package
in Pa
.PackageList
:
843 # Key of DEC's Pcds dictionary is PcdCName, TokenSpaceGuid, PcdType
844 if (Pcd
[0], Pcd
[1], PcdType
) in Package
.Pcds
:
846 for Type
in PcdTypeSet
:
847 if (Pcd
[0], Pcd
[1], Type
) in Package
.Pcds
:
851 "Type [%s] of PCD [%s.%s] in DSC file doesn't match the type [%s] defined in DEC file." \
852 % (Pa
.Platform
.Pcds
[Pcd
].Type
, Pcd
[1], Pcd
[0], Type
),
857 UnusedPcd
.setdefault(Pcd
, []).append(Pa
.Arch
)
859 for Pcd
in UnusedPcd
:
862 "The PCD was not specified by any INF module in the platform for the given architecture.\n"
863 "\tPCD: [%s.%s]\n\tPlatform: [%s]\n\tArch: %s"
864 % (Pcd
[1], Pcd
[0], os
.path
.basename(str(self
.MetaFile
)), str(UnusedPcd
[Pcd
])),
869 return "%s [%s]" % (self
.MetaFile
, ", ".join(self
.ArchList
))
871 ## Return the directory to store FV files
874 return path
.join(self
.BuildDir
, TAB_FV_DIRECTORY
)
876 ## Return the directory to store all intermediate and final files built
879 return self
.AutoGenObjectList
[0].BuildDir
881 ## Return the build output directory platform specifies
884 return self
.Platform
.OutputDirectory
886 ## Return platform name
889 return self
.Platform
.PlatformName
891 ## Return meta-file GUID
894 return self
.Platform
.Guid
896 ## Return platform version
899 return self
.Platform
.Version
901 ## Return paths of tools
903 def ToolDefinition(self
):
904 return self
.AutoGenObjectList
[0].ToolDefinition
906 ## Return directory of platform makefile
908 # @retval string Makefile directory
911 def MakeFileDir(self
):
914 ## Return build command string
916 # @retval string Build command string
919 def BuildCommand(self
):
920 # BuildCommand should be all the same. So just get one from platform AutoGen
921 return self
.AutoGenObjectList
[0].BuildCommand
923 ## Check the PCDs token value conflict in each DEC file.
925 # Will cause build break and raise error message while two PCDs conflict.
929 def _CheckAllPcdsTokenValueConflict(self
):
930 for Pa
in self
.AutoGenObjectList
:
931 for Package
in Pa
.PackageList
:
932 PcdList
= Package
.Pcds
.values()
933 PcdList
.sort(key
=lambda x
: int(x
.TokenValue
, 0))
935 while (Count
< len(PcdList
) - 1) :
936 Item
= PcdList
[Count
]
937 ItemNext
= PcdList
[Count
+ 1]
939 # Make sure in the same token space the TokenValue should be unique
941 if (int(Item
.TokenValue
, 0) == int(ItemNext
.TokenValue
, 0)):
942 SameTokenValuePcdList
= []
943 SameTokenValuePcdList
.append(Item
)
944 SameTokenValuePcdList
.append(ItemNext
)
945 RemainPcdListLength
= len(PcdList
) - Count
- 2
946 for ValueSameCount
in range(RemainPcdListLength
):
947 if int(PcdList
[len(PcdList
) - RemainPcdListLength
+ ValueSameCount
].TokenValue
, 0) == int(Item
.TokenValue
, 0):
948 SameTokenValuePcdList
.append(PcdList
[len(PcdList
) - RemainPcdListLength
+ ValueSameCount
])
952 # Sort same token value PCD list with TokenGuid and TokenCName
954 SameTokenValuePcdList
.sort(key
=lambda x
: "%s.%s" % (x
.TokenSpaceGuidCName
, x
.TokenCName
))
955 SameTokenValuePcdListCount
= 0
956 while (SameTokenValuePcdListCount
< len(SameTokenValuePcdList
) - 1):
958 TemListItem
= SameTokenValuePcdList
[SameTokenValuePcdListCount
]
959 TemListItemNext
= SameTokenValuePcdList
[SameTokenValuePcdListCount
+ 1]
961 if (TemListItem
.TokenSpaceGuidCName
== TemListItemNext
.TokenSpaceGuidCName
) and (TemListItem
.TokenCName
!= TemListItemNext
.TokenCName
):
962 for PcdItem
in GlobalData
.MixedPcd
:
963 if (TemListItem
.TokenCName
, TemListItem
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
] or \
964 (TemListItemNext
.TokenCName
, TemListItemNext
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
970 "The TokenValue [%s] of PCD [%s.%s] is conflict with: [%s.%s] in %s"\
971 % (TemListItem
.TokenValue
, TemListItem
.TokenSpaceGuidCName
, TemListItem
.TokenCName
, TemListItemNext
.TokenSpaceGuidCName
, TemListItemNext
.TokenCName
, Package
),
974 SameTokenValuePcdListCount
+= 1
975 Count
+= SameTokenValuePcdListCount
978 PcdList
= Package
.Pcds
.values()
979 PcdList
.sort(key
=lambda x
: "%s.%s" % (x
.TokenSpaceGuidCName
, x
.TokenCName
))
981 while (Count
< len(PcdList
) - 1) :
982 Item
= PcdList
[Count
]
983 ItemNext
= PcdList
[Count
+ 1]
985 # Check PCDs with same TokenSpaceGuidCName.TokenCName have same token value as well.
987 if (Item
.TokenSpaceGuidCName
== ItemNext
.TokenSpaceGuidCName
) and (Item
.TokenCName
== ItemNext
.TokenCName
) and (int(Item
.TokenValue
, 0) != int(ItemNext
.TokenValue
, 0)):
991 "The TokenValue [%s] of PCD [%s.%s] in %s defined in two places should be same as well."\
992 % (Item
.TokenValue
, Item
.TokenSpaceGuidCName
, Item
.TokenCName
, Package
),
996 ## Generate fds command
998 def GenFdsCommand(self
):
999 return (GenMake
.TopLevelMakefile(self
)._TEMPLATE
_.Replace(GenMake
.TopLevelMakefile(self
)._TemplateDict
)).strip()
1002 def GenFdsCommandDict(self
):
1004 LogLevel
= EdkLogger
.GetLevel()
1005 if LogLevel
== EdkLogger
.VERBOSE
:
1006 FdsCommandDict
["verbose"] = True
1007 elif LogLevel
<= EdkLogger
.DEBUG_9
:
1008 FdsCommandDict
["debug"] = LogLevel
- 1
1009 elif LogLevel
== EdkLogger
.QUIET
:
1010 FdsCommandDict
["quiet"] = True
1012 if GlobalData
.gEnableGenfdsMultiThread
:
1013 FdsCommandDict
["GenfdsMultiThread"] = True
1014 if GlobalData
.gIgnoreSource
:
1015 FdsCommandDict
["IgnoreSources"] = True
1017 FdsCommandDict
["OptionPcd"] = []
1018 for pcd
in GlobalData
.BuildOptionPcd
:
1020 pcdname
= '.'.join(pcd
[0:3])
1022 pcdname
= '.'.join(pcd
[0:2])
1023 if pcd
[3].startswith('{'):
1024 FdsCommandDict
["OptionPcd"].append(pcdname
+ '=' + 'H' + '"' + pcd
[3] + '"')
1026 FdsCommandDict
["OptionPcd"].append(pcdname
+ '=' + pcd
[3])
1029 # macros passed to GenFds
1031 MacroDict
.update(GlobalData
.gGlobalDefines
)
1032 MacroDict
.update(GlobalData
.gCommandLineDefines
)
1033 for MacroName
in MacroDict
:
1034 if MacroDict
[MacroName
] != "":
1035 MacroList
.append('"%s=%s"' % (MacroName
, MacroDict
[MacroName
].replace('\\', '\\\\')))
1037 MacroList
.append('"%s"' % MacroName
)
1038 FdsCommandDict
["macro"] = MacroList
1040 FdsCommandDict
["fdf_file"] = [self
.FdfFile
]
1041 FdsCommandDict
["build_target"] = self
.BuildTarget
1042 FdsCommandDict
["toolchain_tag"] = self
.ToolChain
1043 FdsCommandDict
["active_platform"] = str(self
)
1045 FdsCommandDict
["conf_directory"] = GlobalData
.gConfDirectory
1046 FdsCommandDict
["build_architecture_list"] = ','.join(self
.ArchList
)
1047 FdsCommandDict
["platform_build_directory"] = self
.BuildDir
1049 FdsCommandDict
["fd"] = self
.FdTargetList
1050 FdsCommandDict
["fv"] = self
.FvTargetList
1051 FdsCommandDict
["cap"] = self
.CapTargetList
1052 return FdsCommandDict
1054 ## Create makefile for the platform and modules in it
1056 # @param CreateDepsMakeFile Flag indicating if the makefile for
1057 # modules will be created as well
1059 def CreateMakeFile(self
, CreateDepsMakeFile
=False):
1060 if not CreateDepsMakeFile
:
1062 for Pa
in self
.AutoGenObjectList
:
1063 Pa
.CreateMakeFile(True)
1065 ## Create autogen code for platform and modules
1067 # Since there's no autogen code for platform, this method will do nothing
1068 # if CreateModuleCodeFile is set to False.
1070 # @param CreateDepsCodeFile Flag indicating if creating module's
1071 # autogen code file or not
1073 def CreateCodeFile(self
, CreateDepsCodeFile
=False):
1074 if not CreateDepsCodeFile
:
1076 for Pa
in self
.AutoGenObjectList
:
1077 Pa
.CreateCodeFile(True)
1079 ## Create AsBuilt INF file the platform
1081 def CreateAsBuiltInf(self
):
1085 ## AutoGen class for platform
1087 # PlatformAutoGen class will process the original information in platform
1088 # file in order to generate makefile for platform.
1090 class PlatformAutoGen(AutoGen
):
1091 # call super().__init__ then call the worker function with different parameter count
1092 def __init__(self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
1093 if not hasattr(self
, "_Init"):
1094 self
._InitWorker
(Workspace
, MetaFile
, Target
, Toolchain
, Arch
)
1097 # Used to store all PCDs for both PEI and DXE phase, in order to generate
1098 # correct PCD database
1101 _NonDynaPcdList_
= []
1105 # The priority list while override build option
1107 PrioList
= {"0x11111" : 16, # TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE (Highest)
1108 "0x01111" : 15, # ******_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
1109 "0x10111" : 14, # TARGET_*********_ARCH_COMMANDTYPE_ATTRIBUTE
1110 "0x00111" : 13, # ******_*********_ARCH_COMMANDTYPE_ATTRIBUTE
1111 "0x11011" : 12, # TARGET_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE
1112 "0x01011" : 11, # ******_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE
1113 "0x10011" : 10, # TARGET_*********_****_COMMANDTYPE_ATTRIBUTE
1114 "0x00011" : 9, # ******_*********_****_COMMANDTYPE_ATTRIBUTE
1115 "0x11101" : 8, # TARGET_TOOLCHAIN_ARCH_***********_ATTRIBUTE
1116 "0x01101" : 7, # ******_TOOLCHAIN_ARCH_***********_ATTRIBUTE
1117 "0x10101" : 6, # TARGET_*********_ARCH_***********_ATTRIBUTE
1118 "0x00101" : 5, # ******_*********_ARCH_***********_ATTRIBUTE
1119 "0x11001" : 4, # TARGET_TOOLCHAIN_****_***********_ATTRIBUTE
1120 "0x01001" : 3, # ******_TOOLCHAIN_****_***********_ATTRIBUTE
1121 "0x10001" : 2, # TARGET_*********_****_***********_ATTRIBUTE
1122 "0x00001" : 1} # ******_*********_****_***********_ATTRIBUTE (Lowest)
1124 ## Initialize PlatformAutoGen
1127 # @param Workspace WorkspaceAutoGen object
1128 # @param PlatformFile Platform file (DSC file)
1129 # @param Target Build target (DEBUG, RELEASE)
1130 # @param Toolchain Name of tool chain
1131 # @param Arch arch of the platform supports
1133 def _InitWorker(self
, Workspace
, PlatformFile
, Target
, Toolchain
, Arch
):
1134 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "AutoGen platform [%s] [%s]" % (PlatformFile
, Arch
))
1135 GlobalData
.gProcessingFile
= "%s [%s, %s, %s]" % (PlatformFile
, Arch
, Toolchain
, Target
)
1137 self
.MetaFile
= PlatformFile
1138 self
.Workspace
= Workspace
1139 self
.WorkspaceDir
= Workspace
.WorkspaceDir
1140 self
.ToolChain
= Toolchain
1141 self
.BuildTarget
= Target
1143 self
.SourceDir
= PlatformFile
.SubDir
1144 self
.SourceOverrideDir
= None
1145 self
.FdTargetList
= self
.Workspace
.FdTargetList
1146 self
.FvTargetList
= self
.Workspace
.FvTargetList
1147 self
.AllPcdList
= []
1148 # get the original module/package/platform objects
1149 self
.BuildDatabase
= Workspace
.BuildDatabase
1150 self
.DscBuildDataObj
= Workspace
.Platform
1152 # flag indicating if the makefile/C-code file has been created or not
1153 self
.IsMakeFileCreated
= False
1155 self
._DynamicPcdList
= None # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
1156 self
._NonDynamicPcdList
= None # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
1158 self
._AsBuildInfList
= []
1159 self
._AsBuildModuleList
= []
1161 self
.VariableInfo
= None
1163 if GlobalData
.gFdfParser
is not None:
1164 self
._AsBuildInfList
= GlobalData
.gFdfParser
.Profile
.InfList
1165 for Inf
in self
._AsBuildInfList
:
1166 InfClass
= PathClass(NormPath(Inf
), GlobalData
.gWorkspace
, self
.Arch
)
1167 M
= self
.BuildDatabase
[InfClass
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1168 if not M
.IsBinaryModule
:
1170 self
._AsBuildModuleList
.append(InfClass
)
1171 # get library/modules for build
1172 self
.LibraryBuildDirectoryList
= []
1173 self
.ModuleBuildDirectoryList
= []
1177 @cached_class_function
1179 return "%s [%s]" % (self
.MetaFile
, self
.Arch
)
1181 ## Create autogen code for platform and modules
1183 # Since there's no autogen code for platform, this method will do nothing
1184 # if CreateModuleCodeFile is set to False.
1186 # @param CreateModuleCodeFile Flag indicating if creating module's
1187 # autogen code file or not
1189 @cached_class_function
1190 def CreateCodeFile(self
, CreateModuleCodeFile
=False):
1191 # only module has code to be greated, so do nothing if CreateModuleCodeFile is False
1192 if not CreateModuleCodeFile
:
1195 for Ma
in self
.ModuleAutoGenList
:
1196 Ma
.CreateCodeFile(True)
1198 ## Generate Fds Command
1200 def GenFdsCommand(self
):
1201 return self
.Workspace
.GenFdsCommand
1203 ## Create makefile for the platform and modules in it
1205 # @param CreateModuleMakeFile Flag indicating if the makefile for
1206 # modules will be created as well
1208 def CreateMakeFile(self
, CreateModuleMakeFile
=False, FfsCommand
= {}):
1209 if CreateModuleMakeFile
:
1210 for Ma
in self
._MaList
:
1211 key
= (Ma
.MetaFile
.File
, self
.Arch
)
1212 if key
in FfsCommand
:
1213 Ma
.CreateMakeFile(True, FfsCommand
[key
])
1215 Ma
.CreateMakeFile(True)
1217 # no need to create makefile for the platform more than once
1218 if self
.IsMakeFileCreated
:
1221 # create library/module build dirs for platform
1222 Makefile
= GenMake
.PlatformMakefile(self
)
1223 self
.LibraryBuildDirectoryList
= Makefile
.GetLibraryBuildDirectoryList()
1224 self
.ModuleBuildDirectoryList
= Makefile
.GetModuleBuildDirectoryList()
1226 self
.IsMakeFileCreated
= True
1228 ## Deal with Shared FixedAtBuild Pcds
1230 def CollectFixedAtBuildPcds(self
):
1231 for LibAuto
in self
.LibraryAutoGenList
:
1232 FixedAtBuildPcds
= {}
1233 ShareFixedAtBuildPcdsSameValue
= {}
1234 for Module
in LibAuto
.ReferenceModules
:
1235 for Pcd
in set(Module
.FixedAtBuildPcds
+ LibAuto
.FixedAtBuildPcds
):
1236 DefaultValue
= Pcd
.DefaultValue
1237 # Cover the case: DSC component override the Pcd value and the Pcd only used in one Lib
1238 if Pcd
in Module
.LibraryPcdList
:
1239 Index
= Module
.LibraryPcdList
.index(Pcd
)
1240 DefaultValue
= Module
.LibraryPcdList
[Index
].DefaultValue
1241 key
= ".".join((Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
))
1242 if key
not in FixedAtBuildPcds
:
1243 ShareFixedAtBuildPcdsSameValue
[key
] = True
1244 FixedAtBuildPcds
[key
] = DefaultValue
1246 if FixedAtBuildPcds
[key
] != DefaultValue
:
1247 ShareFixedAtBuildPcdsSameValue
[key
] = False
1248 for Pcd
in LibAuto
.FixedAtBuildPcds
:
1249 key
= ".".join((Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
))
1250 if (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
) not in self
.NonDynamicPcdDict
:
1253 DscPcd
= self
.NonDynamicPcdDict
[(Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
)]
1254 if DscPcd
.Type
!= TAB_PCDS_FIXED_AT_BUILD
:
1256 if key
in ShareFixedAtBuildPcdsSameValue
and ShareFixedAtBuildPcdsSameValue
[key
]:
1257 LibAuto
.ConstPcd
[key
] = FixedAtBuildPcds
[key
]
1259 def CollectVariables(self
, DynamicPcdSet
):
1262 if self
.Workspace
.FdfFile
:
1263 FdDict
= self
.Workspace
.FdfProfile
.FdDict
[GlobalData
.gFdfParser
.CurrentFdName
]
1264 for FdRegion
in FdDict
.RegionList
:
1265 for item
in FdRegion
.RegionDataList
:
1266 if self
.Platform
.VpdToolGuid
.strip() and self
.Platform
.VpdToolGuid
in item
:
1267 VpdRegionSize
= FdRegion
.Size
1268 VpdRegionBase
= FdRegion
.Offset
1271 VariableInfo
= VariableMgr(self
.DscBuildDataObj
._GetDefaultStores
(), self
.DscBuildDataObj
.SkuIds
)
1272 VariableInfo
.SetVpdRegionMaxSize(VpdRegionSize
)
1273 VariableInfo
.SetVpdRegionOffset(VpdRegionBase
)
1275 for Pcd
in DynamicPcdSet
:
1276 pcdname
= ".".join((Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
))
1277 for SkuName
in Pcd
.SkuInfoList
:
1278 Sku
= Pcd
.SkuInfoList
[SkuName
]
1280 if SkuId
is None or SkuId
== '':
1282 if len(Sku
.VariableName
) > 0:
1283 if Sku
.VariableAttribute
and 'NV' not in Sku
.VariableAttribute
:
1285 VariableGuidStructure
= Sku
.VariableGuidValue
1286 VariableGuid
= GuidStructureStringToGuidString(VariableGuidStructure
)
1287 for StorageName
in Sku
.DefaultStoreDict
:
1288 VariableInfo
.append_variable(var_info(Index
, pcdname
, StorageName
, SkuName
, StringToArray(Sku
.VariableName
), VariableGuid
, Sku
.VariableOffset
, Sku
.VariableAttribute
, Sku
.HiiDefaultValue
, Sku
.DefaultStoreDict
[StorageName
] if Pcd
.DatumType
in TAB_PCD_NUMERIC_TYPES
else StringToArray(Sku
.DefaultStoreDict
[StorageName
]), Pcd
.DatumType
, Pcd
.CustomAttribute
['DscPosition'], Pcd
.CustomAttribute
.get('IsStru',False)))
1292 def UpdateNVStoreMaxSize(self
, OrgVpdFile
):
1293 if self
.VariableInfo
:
1294 VpdMapFilePath
= os
.path
.join(self
.BuildDir
, TAB_FV_DIRECTORY
, "%s.map" % self
.Platform
.VpdToolGuid
)
1295 PcdNvStoreDfBuffer
= [item
for item
in self
._DynamicPcdList
if item
.TokenCName
== "PcdNvStoreDefaultValueBuffer" and item
.TokenSpaceGuidCName
== "gEfiMdeModulePkgTokenSpaceGuid"]
1297 if PcdNvStoreDfBuffer
:
1298 if os
.path
.exists(VpdMapFilePath
):
1299 OrgVpdFile
.Read(VpdMapFilePath
)
1300 PcdItems
= OrgVpdFile
.GetOffset(PcdNvStoreDfBuffer
[0])
1301 NvStoreOffset
= PcdItems
.values()[0].strip() if PcdItems
else '0'
1303 EdkLogger
.error("build", FILE_READ_FAILURE
, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath
)
1305 NvStoreOffset
= int(NvStoreOffset
, 16) if NvStoreOffset
.upper().startswith("0X") else int(NvStoreOffset
)
1306 default_skuobj
= PcdNvStoreDfBuffer
[0].SkuInfoList
.get(TAB_DEFAULT
)
1307 maxsize
= self
.VariableInfo
.VpdRegionSize
- NvStoreOffset
if self
.VariableInfo
.VpdRegionSize
else len(default_skuobj
.DefaultValue
.split(","))
1308 var_data
= self
.VariableInfo
.PatchNVStoreDefaultMaxSize(maxsize
)
1310 if var_data
and default_skuobj
:
1311 default_skuobj
.DefaultValue
= var_data
1312 PcdNvStoreDfBuffer
[0].DefaultValue
= var_data
1313 PcdNvStoreDfBuffer
[0].SkuInfoList
.clear()
1314 PcdNvStoreDfBuffer
[0].SkuInfoList
[TAB_DEFAULT
] = default_skuobj
1315 PcdNvStoreDfBuffer
[0].MaxDatumSize
= str(len(default_skuobj
.DefaultValue
.split(",")))
1319 ## Collect dynamic PCDs
1321 # Gather dynamic PCDs list from each module and their settings from platform
1322 # This interface should be invoked explicitly when platform action is created.
1324 def CollectPlatformDynamicPcds(self
):
1325 for key
in self
.Platform
.Pcds
:
1326 for SinglePcd
in GlobalData
.MixedPcd
:
1327 if (self
.Platform
.Pcds
[key
].TokenCName
, self
.Platform
.Pcds
[key
].TokenSpaceGuidCName
) == SinglePcd
:
1328 for item
in GlobalData
.MixedPcd
[SinglePcd
]:
1329 Pcd_Type
= item
[0].split('_')[-1]
1330 if (Pcd_Type
== self
.Platform
.Pcds
[key
].Type
) or (Pcd_Type
== TAB_PCDS_DYNAMIC_EX
and self
.Platform
.Pcds
[key
].Type
in PCD_DYNAMIC_EX_TYPE_SET
) or \
1331 (Pcd_Type
== TAB_PCDS_DYNAMIC
and self
.Platform
.Pcds
[key
].Type
in PCD_DYNAMIC_TYPE_SET
):
1332 Value
= self
.Platform
.Pcds
[key
]
1333 Value
.TokenCName
= self
.Platform
.Pcds
[key
].TokenCName
+ '_' + Pcd_Type
1335 newkey
= (Value
.TokenCName
, key
[1])
1337 newkey
= (Value
.TokenCName
, key
[1], key
[2])
1338 del self
.Platform
.Pcds
[key
]
1339 self
.Platform
.Pcds
[newkey
] = Value
1343 # for gathering error information
1344 NoDatumTypePcdList
= set()
1346 for InfName
in self
._AsBuildInfList
:
1347 InfName
= mws
.join(self
.WorkspaceDir
, InfName
)
1348 FdfModuleList
.append(os
.path
.normpath(InfName
))
1349 for M
in self
._MaList
:
1350 # F is the Module for which M is the module autogen
1351 for PcdFromModule
in M
.ModulePcdList
+ M
.LibraryPcdList
:
1352 # make sure that the "VOID*" kind of datum has MaxDatumSize set
1353 if PcdFromModule
.DatumType
== TAB_VOID
and not PcdFromModule
.MaxDatumSize
:
1354 NoDatumTypePcdList
.add("%s.%s [%s]" % (PcdFromModule
.TokenSpaceGuidCName
, PcdFromModule
.TokenCName
, M
.MetaFile
))
1356 # Check the PCD from Binary INF or Source INF
1357 if M
.IsBinaryModule
== True:
1358 PcdFromModule
.IsFromBinaryInf
= True
1360 # Check the PCD from DSC or not
1361 PcdFromModule
.IsFromDsc
= (PcdFromModule
.TokenCName
, PcdFromModule
.TokenSpaceGuidCName
) in self
.Platform
.Pcds
1363 if PcdFromModule
.Type
in PCD_DYNAMIC_TYPE_SET
or PcdFromModule
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
1364 if M
.MetaFile
.Path
not in FdfModuleList
:
1365 # If one of the Source built modules listed in the DSC is not listed
1366 # in FDF modules, and the INF lists a PCD can only use the PcdsDynamic
1367 # access method (it is only listed in the DEC file that declares the
1368 # PCD as PcdsDynamic), then build tool will report warning message
1369 # notify the PI that they are attempting to build a module that must
1370 # be included in a flash image in order to be functional. These Dynamic
1371 # PCD will not be added into the Database unless it is used by other
1372 # modules that are included in the FDF file.
1373 if PcdFromModule
.Type
in PCD_DYNAMIC_TYPE_SET
and \
1374 PcdFromModule
.IsFromBinaryInf
== False:
1375 # Print warning message to let the developer make a determine.
1377 # If one of the Source built modules listed in the DSC is not listed in
1378 # FDF modules, and the INF lists a PCD can only use the PcdsDynamicEx
1379 # access method (it is only listed in the DEC file that declares the
1380 # PCD as PcdsDynamicEx), then DO NOT break the build; DO NOT add the
1381 # PCD to the Platform's PCD Database.
1382 if PcdFromModule
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
1385 # If a dynamic PCD used by a PEM module/PEI module & DXE module,
1386 # it should be stored in Pcd PEI database, If a dynamic only
1387 # used by DXE module, it should be stored in DXE PCD database.
1388 # The default Phase is DXE
1390 if M
.ModuleType
in SUP_MODULE_SET_PEI
:
1391 PcdFromModule
.Phase
= "PEI"
1392 if PcdFromModule
not in self
._DynaPcdList
_:
1393 self
._DynaPcdList
_.append(PcdFromModule
)
1394 elif PcdFromModule
.Phase
== 'PEI':
1395 # overwrite any the same PCD existing, if Phase is PEI
1396 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1397 self
._DynaPcdList
_[Index
] = PcdFromModule
1398 elif PcdFromModule
not in self
._NonDynaPcdList
_:
1399 self
._NonDynaPcdList
_.append(PcdFromModule
)
1400 elif PcdFromModule
in self
._NonDynaPcdList
_ and PcdFromModule
.IsFromBinaryInf
== True:
1401 Index
= self
._NonDynaPcdList
_.index(PcdFromModule
)
1402 if self
._NonDynaPcdList
_[Index
].IsFromBinaryInf
== False:
1403 #The PCD from Binary INF will override the same one from source INF
1404 self
._NonDynaPcdList
_.remove (self
._NonDynaPcdList
_[Index
])
1405 PcdFromModule
.Pending
= False
1406 self
._NonDynaPcdList
_.append (PcdFromModule
)
1407 DscModuleSet
= {os
.path
.normpath(ModuleInf
.Path
) for ModuleInf
in self
.Platform
.Modules
}
1408 # add the PCD from modules that listed in FDF but not in DSC to Database
1409 for InfName
in FdfModuleList
:
1410 if InfName
not in DscModuleSet
:
1411 InfClass
= PathClass(InfName
)
1412 M
= self
.BuildDatabase
[InfClass
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1413 # If a module INF in FDF but not in current arch's DSC module list, it must be module (either binary or source)
1414 # for different Arch. PCDs in source module for different Arch is already added before, so skip the source module here.
1415 # For binary module, if in current arch, we need to list the PCDs into database.
1416 if not M
.IsBinaryModule
:
1418 # Override the module PCD setting by platform setting
1419 ModulePcdList
= self
.ApplyPcdSetting(M
, M
.Pcds
)
1420 for PcdFromModule
in ModulePcdList
:
1421 PcdFromModule
.IsFromBinaryInf
= True
1422 PcdFromModule
.IsFromDsc
= False
1423 # Only allow the DynamicEx and Patchable PCD in AsBuild INF
1424 if PcdFromModule
.Type
not in PCD_DYNAMIC_EX_TYPE_SET
and PcdFromModule
.Type
not in TAB_PCDS_PATCHABLE_IN_MODULE
:
1425 EdkLogger
.error("build", AUTOGEN_ERROR
, "PCD setting error",
1427 ExtraData
="\n\tExisted %s PCD %s in:\n\t\t%s\n"
1428 % (PcdFromModule
.Type
, PcdFromModule
.TokenCName
, InfName
))
1429 # make sure that the "VOID*" kind of datum has MaxDatumSize set
1430 if PcdFromModule
.DatumType
== TAB_VOID
and not PcdFromModule
.MaxDatumSize
:
1431 NoDatumTypePcdList
.add("%s.%s [%s]" % (PcdFromModule
.TokenSpaceGuidCName
, PcdFromModule
.TokenCName
, InfName
))
1432 if M
.ModuleType
in SUP_MODULE_SET_PEI
:
1433 PcdFromModule
.Phase
= "PEI"
1434 if PcdFromModule
not in self
._DynaPcdList
_ and PcdFromModule
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
1435 self
._DynaPcdList
_.append(PcdFromModule
)
1436 elif PcdFromModule
not in self
._NonDynaPcdList
_ and PcdFromModule
.Type
in TAB_PCDS_PATCHABLE_IN_MODULE
:
1437 self
._NonDynaPcdList
_.append(PcdFromModule
)
1438 if PcdFromModule
in self
._DynaPcdList
_ and PcdFromModule
.Phase
== 'PEI' and PcdFromModule
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
1439 # Overwrite the phase of any the same PCD existing, if Phase is PEI.
1440 # It is to solve the case that a dynamic PCD used by a PEM module/PEI
1441 # module & DXE module at a same time.
1442 # Overwrite the type of the PCDs in source INF by the type of AsBuild
1443 # INF file as DynamicEx.
1444 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1445 self
._DynaPcdList
_[Index
].Phase
= PcdFromModule
.Phase
1446 self
._DynaPcdList
_[Index
].Type
= PcdFromModule
.Type
1447 for PcdFromModule
in self
._NonDynaPcdList
_:
1448 # If a PCD is not listed in the DSC file, but binary INF files used by
1449 # this platform all (that use this PCD) list the PCD in a [PatchPcds]
1450 # section, AND all source INF files used by this platform the build
1451 # that use the PCD list the PCD in either a [Pcds] or [PatchPcds]
1452 # section, then the tools must NOT add the PCD to the Platform's PCD
1453 # Database; the build must assign the access method for this PCD as
1454 # PcdsPatchableInModule.
1455 if PcdFromModule
not in self
._DynaPcdList
_:
1457 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1458 if PcdFromModule
.IsFromDsc
== False and \
1459 PcdFromModule
.Type
in TAB_PCDS_PATCHABLE_IN_MODULE
and \
1460 PcdFromModule
.IsFromBinaryInf
== True and \
1461 self
._DynaPcdList
_[Index
].IsFromBinaryInf
== False:
1462 Index
= self
._DynaPcdList
_.index(PcdFromModule
)
1463 self
._DynaPcdList
_.remove (self
._DynaPcdList
_[Index
])
1465 # print out error information and break the build, if error found
1466 if len(NoDatumTypePcdList
) > 0:
1467 NoDatumTypePcdListString
= "\n\t\t".join(NoDatumTypePcdList
)
1468 EdkLogger
.error("build", AUTOGEN_ERROR
, "PCD setting error",
1470 ExtraData
="\n\tPCD(s) without MaxDatumSize:\n\t\t%s\n"
1471 % NoDatumTypePcdListString
)
1472 self
._NonDynamicPcdList
= self
._NonDynaPcdList
_
1473 self
._DynamicPcdList
= self
._DynaPcdList
_
1475 # Sort dynamic PCD list to:
1476 # 1) If PCD's datum type is VOID* and value is unicode string which starts with L, the PCD item should
1477 # try to be put header of dynamicd List
1478 # 2) If PCD is HII type, the PCD item should be put after unicode type PCD
1480 # The reason of sorting is make sure the unicode string is in double-byte alignment in string table.
1482 UnicodePcdArray
= set()
1484 OtherPcdArray
= set()
1486 VpdFile
= VpdInfoFile
.VpdInfoFile()
1487 NeedProcessVpdMapFile
= False
1489 for pcd
in self
.Platform
.Pcds
:
1490 if pcd
not in self
._PlatformPcds
:
1491 self
._PlatformPcds
[pcd
] = self
.Platform
.Pcds
[pcd
]
1493 for item
in self
._PlatformPcds
:
1494 if self
._PlatformPcds
[item
].DatumType
and self
._PlatformPcds
[item
].DatumType
not in [TAB_UINT8
, TAB_UINT16
, TAB_UINT32
, TAB_UINT64
, TAB_VOID
, "BOOLEAN"]:
1495 self
._PlatformPcds
[item
].DatumType
= TAB_VOID
1497 if (self
.Workspace
.ArchList
[-1] == self
.Arch
):
1498 for Pcd
in self
._DynamicPcdList
:
1499 # just pick the a value to determine whether is unicode string type
1500 Sku
= Pcd
.SkuInfoList
.values()[0]
1501 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1503 if Pcd
.DatumType
not in [TAB_UINT8
, TAB_UINT16
, TAB_UINT32
, TAB_UINT64
, TAB_VOID
, "BOOLEAN"]:
1504 Pcd
.DatumType
= TAB_VOID
1506 # if found PCD which datum value is unicode string the insert to left size of UnicodeIndex
1507 # if found HII type PCD then insert to right of UnicodeIndex
1508 if Pcd
.Type
in [TAB_PCDS_DYNAMIC_VPD
, TAB_PCDS_DYNAMIC_EX_VPD
]:
1509 VpdPcdDict
[(Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
)] = Pcd
1511 #Collect DynamicHii PCD values and assign it to DynamicExVpd PCD gEfiMdeModulePkgTokenSpaceGuid.PcdNvStoreDefaultValueBuffer
1512 PcdNvStoreDfBuffer
= VpdPcdDict
.get(("PcdNvStoreDefaultValueBuffer", "gEfiMdeModulePkgTokenSpaceGuid"))
1513 if PcdNvStoreDfBuffer
:
1514 self
.VariableInfo
= self
.CollectVariables(self
._DynamicPcdList
)
1515 vardump
= self
.VariableInfo
.dump()
1518 #According to PCD_DATABASE_INIT in edk2\MdeModulePkg\Include\Guid\PcdDataBaseSignatureGuid.h,
1519 #the max size for string PCD should not exceed USHRT_MAX 65535(0xffff).
1520 #typedef UINT16 SIZE_INFO;
1521 #//SIZE_INFO SizeTable[];
1522 if len(vardump
.split(",")) > 0xffff:
1523 EdkLogger
.error("build", RESOURCE_OVERFLOW
, 'The current length of PCD %s value is %d, it exceeds to the max size of String PCD.' %(".".join([PcdNvStoreDfBuffer
.TokenSpaceGuidCName
,PcdNvStoreDfBuffer
.TokenCName
]) ,len(vardump
.split(","))))
1524 PcdNvStoreDfBuffer
.DefaultValue
= vardump
1525 for skuname
in PcdNvStoreDfBuffer
.SkuInfoList
:
1526 PcdNvStoreDfBuffer
.SkuInfoList
[skuname
].DefaultValue
= vardump
1527 PcdNvStoreDfBuffer
.MaxDatumSize
= str(len(vardump
.split(",")))
1529 #If the end user define [DefaultStores] and [XXX.Menufacturing] in DSC, but forget to configure PcdNvStoreDefaultValueBuffer to PcdsDynamicVpd
1530 if [Pcd
for Pcd
in self
._DynamicPcdList
if Pcd
.UserDefinedDefaultStoresFlag
]:
1531 EdkLogger
.warn("build", "PcdNvStoreDefaultValueBuffer should be defined as PcdsDynamicExVpd in dsc file since the DefaultStores is enabled for this platform.\n%s" %self
.Platform
.MetaFile
.Path
)
1532 PlatformPcds
= sorted(self
._PlatformPcds
.keys())
1534 # Add VPD type PCD into VpdFile and determine whether the VPD PCD need to be fixed up.
1537 for PcdKey
in PlatformPcds
:
1538 Pcd
= self
._PlatformPcds
[PcdKey
]
1539 if Pcd
.Type
in [TAB_PCDS_DYNAMIC_VPD
, TAB_PCDS_DYNAMIC_EX_VPD
] and \
1540 PcdKey
in VpdPcdDict
:
1541 Pcd
= VpdPcdDict
[PcdKey
]
1543 DefaultSku
= Pcd
.SkuInfoList
.get(TAB_DEFAULT
)
1545 PcdValue
= DefaultSku
.DefaultValue
1546 if PcdValue
not in SkuValueMap
:
1547 SkuValueMap
[PcdValue
] = []
1548 VpdFile
.Add(Pcd
, TAB_DEFAULT
, DefaultSku
.VpdOffset
)
1549 SkuValueMap
[PcdValue
].append(DefaultSku
)
1551 for (SkuName
, Sku
) in Pcd
.SkuInfoList
.items():
1552 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1553 PcdValue
= Sku
.DefaultValue
1555 PcdValue
= Pcd
.DefaultValue
1556 if Sku
.VpdOffset
!= TAB_STAR
:
1557 if PcdValue
.startswith("{"):
1559 elif PcdValue
.startswith("L"):
1564 VpdOffset
= int(Sku
.VpdOffset
)
1567 VpdOffset
= int(Sku
.VpdOffset
, 16)
1569 EdkLogger
.error("build", FORMAT_INVALID
, "Invalid offset value %s for PCD %s.%s." % (Sku
.VpdOffset
, Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
))
1570 if VpdOffset
% Alignment
!= 0:
1571 if PcdValue
.startswith("{"):
1572 EdkLogger
.warn("build", "The offset value of PCD %s.%s is not 8-byte aligned!" %(Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
), File
=self
.MetaFile
)
1574 EdkLogger
.error("build", FORMAT_INVALID
, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
, Alignment
))
1575 if PcdValue
not in SkuValueMap
:
1576 SkuValueMap
[PcdValue
] = []
1577 VpdFile
.Add(Pcd
, SkuName
, Sku
.VpdOffset
)
1578 SkuValueMap
[PcdValue
].append(Sku
)
1579 # if the offset of a VPD is *, then it need to be fixed up by third party tool.
1580 if not NeedProcessVpdMapFile
and Sku
.VpdOffset
== TAB_STAR
:
1581 NeedProcessVpdMapFile
= True
1582 if self
.Platform
.VpdToolGuid
is None or self
.Platform
.VpdToolGuid
== '':
1583 EdkLogger
.error("Build", FILE_NOT_FOUND
, \
1584 "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.")
1586 VpdSkuMap
[PcdKey
] = SkuValueMap
1588 # Fix the PCDs define in VPD PCD section that never referenced by module.
1589 # An example is PCD for signature usage.
1591 for DscPcd
in PlatformPcds
:
1592 DscPcdEntry
= self
._PlatformPcds
[DscPcd
]
1593 if DscPcdEntry
.Type
in [TAB_PCDS_DYNAMIC_VPD
, TAB_PCDS_DYNAMIC_EX_VPD
]:
1594 if not (self
.Platform
.VpdToolGuid
is None or self
.Platform
.VpdToolGuid
== ''):
1596 for VpdPcd
in VpdFile
._VpdArray
:
1597 # This PCD has been referenced by module
1598 if (VpdPcd
.TokenSpaceGuidCName
== DscPcdEntry
.TokenSpaceGuidCName
) and \
1599 (VpdPcd
.TokenCName
== DscPcdEntry
.TokenCName
):
1602 # Not found, it should be signature
1604 # just pick the a value to determine whether is unicode string type
1606 SkuObjList
= DscPcdEntry
.SkuInfoList
.items()
1607 DefaultSku
= DscPcdEntry
.SkuInfoList
.get(TAB_DEFAULT
)
1609 defaultindex
= SkuObjList
.index((TAB_DEFAULT
, DefaultSku
))
1610 SkuObjList
[0], SkuObjList
[defaultindex
] = SkuObjList
[defaultindex
], SkuObjList
[0]
1611 for (SkuName
, Sku
) in SkuObjList
:
1612 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1614 # Need to iterate DEC pcd information to get the value & datumtype
1615 for eachDec
in self
.PackageList
:
1616 for DecPcd
in eachDec
.Pcds
:
1617 DecPcdEntry
= eachDec
.Pcds
[DecPcd
]
1618 if (DecPcdEntry
.TokenSpaceGuidCName
== DscPcdEntry
.TokenSpaceGuidCName
) and \
1619 (DecPcdEntry
.TokenCName
== DscPcdEntry
.TokenCName
):
1620 # Print warning message to let the developer make a determine.
1621 EdkLogger
.warn("build", "Unreferenced vpd pcd used!",
1622 File
=self
.MetaFile
, \
1623 ExtraData
= "PCD: %s.%s used in the DSC file %s is unreferenced." \
1624 %(DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
, self
.Platform
.MetaFile
.Path
))
1626 DscPcdEntry
.DatumType
= DecPcdEntry
.DatumType
1627 DscPcdEntry
.DefaultValue
= DecPcdEntry
.DefaultValue
1628 DscPcdEntry
.TokenValue
= DecPcdEntry
.TokenValue
1629 DscPcdEntry
.TokenSpaceGuidValue
= eachDec
.Guids
[DecPcdEntry
.TokenSpaceGuidCName
]
1630 # Only fix the value while no value provided in DSC file.
1631 if not Sku
.DefaultValue
:
1632 DscPcdEntry
.SkuInfoList
[DscPcdEntry
.SkuInfoList
.keys()[0]].DefaultValue
= DecPcdEntry
.DefaultValue
1634 if DscPcdEntry
not in self
._DynamicPcdList
:
1635 self
._DynamicPcdList
.append(DscPcdEntry
)
1636 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1637 PcdValue
= Sku
.DefaultValue
1639 PcdValue
= DscPcdEntry
.DefaultValue
1640 if Sku
.VpdOffset
!= TAB_STAR
:
1641 if PcdValue
.startswith("{"):
1643 elif PcdValue
.startswith("L"):
1648 VpdOffset
= int(Sku
.VpdOffset
)
1651 VpdOffset
= int(Sku
.VpdOffset
, 16)
1653 EdkLogger
.error("build", FORMAT_INVALID
, "Invalid offset value %s for PCD %s.%s." % (Sku
.VpdOffset
, DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
))
1654 if VpdOffset
% Alignment
!= 0:
1655 if PcdValue
.startswith("{"):
1656 EdkLogger
.warn("build", "The offset value of PCD %s.%s is not 8-byte aligned!" %(DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
), File
=self
.MetaFile
)
1658 EdkLogger
.error("build", FORMAT_INVALID
, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (DscPcdEntry
.TokenSpaceGuidCName
, DscPcdEntry
.TokenCName
, Alignment
))
1659 if PcdValue
not in SkuValueMap
:
1660 SkuValueMap
[PcdValue
] = []
1661 VpdFile
.Add(DscPcdEntry
, SkuName
, Sku
.VpdOffset
)
1662 SkuValueMap
[PcdValue
].append(Sku
)
1663 if not NeedProcessVpdMapFile
and Sku
.VpdOffset
== TAB_STAR
:
1664 NeedProcessVpdMapFile
= True
1665 if DscPcdEntry
.DatumType
== TAB_VOID
and PcdValue
.startswith("L"):
1666 UnicodePcdArray
.add(DscPcdEntry
)
1667 elif len(Sku
.VariableName
) > 0:
1668 HiiPcdArray
.add(DscPcdEntry
)
1670 OtherPcdArray
.add(DscPcdEntry
)
1672 # if the offset of a VPD is *, then it need to be fixed up by third party tool.
1673 VpdSkuMap
[DscPcd
] = SkuValueMap
1674 if (self
.Platform
.FlashDefinition
is None or self
.Platform
.FlashDefinition
== '') and \
1675 VpdFile
.GetCount() != 0:
1676 EdkLogger
.error("build", ATTRIBUTE_NOT_AVAILABLE
,
1677 "Fail to get FLASH_DEFINITION definition in DSC file %s which is required when DSC contains VPD PCD." % str(self
.Platform
.MetaFile
))
1679 if VpdFile
.GetCount() != 0:
1681 self
.FixVpdOffset(VpdFile
)
1683 self
.FixVpdOffset(self
.UpdateNVStoreMaxSize(VpdFile
))
1684 PcdNvStoreDfBuffer
= [item
for item
in self
._DynamicPcdList
if item
.TokenCName
== "PcdNvStoreDefaultValueBuffer" and item
.TokenSpaceGuidCName
== "gEfiMdeModulePkgTokenSpaceGuid"]
1685 if PcdNvStoreDfBuffer
:
1686 PcdName
,PcdGuid
= PcdNvStoreDfBuffer
[0].TokenCName
, PcdNvStoreDfBuffer
[0].TokenSpaceGuidCName
1687 if (PcdName
,PcdGuid
) in VpdSkuMap
:
1688 DefaultSku
= PcdNvStoreDfBuffer
[0].SkuInfoList
.get(TAB_DEFAULT
)
1689 VpdSkuMap
[(PcdName
,PcdGuid
)] = {DefaultSku
.DefaultValue
:[DefaultSku
]}
1691 # Process VPD map file generated by third party BPDG tool
1692 if NeedProcessVpdMapFile
:
1693 VpdMapFilePath
= os
.path
.join(self
.BuildDir
, TAB_FV_DIRECTORY
, "%s.map" % self
.Platform
.VpdToolGuid
)
1694 if os
.path
.exists(VpdMapFilePath
):
1695 VpdFile
.Read(VpdMapFilePath
)
1697 # Fixup TAB_STAR offset
1698 for pcd
in VpdSkuMap
:
1699 vpdinfo
= VpdFile
.GetVpdInfo(pcd
)
1701 # just pick the a value to determine whether is unicode string type
1703 for pcdvalue
in VpdSkuMap
[pcd
]:
1704 for sku
in VpdSkuMap
[pcd
][pcdvalue
]:
1705 for item
in vpdinfo
:
1706 if item
[2] == pcdvalue
:
1707 sku
.VpdOffset
= item
[1]
1709 EdkLogger
.error("build", FILE_READ_FAILURE
, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath
)
1711 # Delete the DynamicPcdList At the last time enter into this function
1712 for Pcd
in self
._DynamicPcdList
:
1713 # just pick the a value to determine whether is unicode string type
1714 Sku
= Pcd
.SkuInfoList
.values()[0]
1715 Sku
.VpdOffset
= Sku
.VpdOffset
.strip()
1717 if Pcd
.DatumType
not in [TAB_UINT8
, TAB_UINT16
, TAB_UINT32
, TAB_UINT64
, TAB_VOID
, "BOOLEAN"]:
1718 Pcd
.DatumType
= TAB_VOID
1720 PcdValue
= Sku
.DefaultValue
1721 if Pcd
.DatumType
== TAB_VOID
and PcdValue
.startswith("L"):
1722 # if found PCD which datum value is unicode string the insert to left size of UnicodeIndex
1723 UnicodePcdArray
.add(Pcd
)
1724 elif len(Sku
.VariableName
) > 0:
1725 # if found HII type PCD then insert to right of UnicodeIndex
1726 HiiPcdArray
.add(Pcd
)
1728 OtherPcdArray
.add(Pcd
)
1729 del self
._DynamicPcdList
[:]
1730 self
._DynamicPcdList
.extend(list(UnicodePcdArray
))
1731 self
._DynamicPcdList
.extend(list(HiiPcdArray
))
1732 self
._DynamicPcdList
.extend(list(OtherPcdArray
))
1733 allskuset
= [(SkuName
, Sku
.SkuId
) for pcd
in self
._DynamicPcdList
for (SkuName
, Sku
) in pcd
.SkuInfoList
.items()]
1734 for pcd
in self
._DynamicPcdList
:
1735 if len(pcd
.SkuInfoList
) == 1:
1736 for (SkuName
, SkuId
) in allskuset
:
1737 if type(SkuId
) in (str, unicode) and eval(SkuId
) == 0 or SkuId
== 0:
1739 pcd
.SkuInfoList
[SkuName
] = copy
.deepcopy(pcd
.SkuInfoList
[TAB_DEFAULT
])
1740 pcd
.SkuInfoList
[SkuName
].SkuId
= SkuId
1741 pcd
.SkuInfoList
[SkuName
].SkuIdName
= SkuName
1742 self
.AllPcdList
= self
._NonDynamicPcdList
+ self
._DynamicPcdList
1744 def FixVpdOffset(self
, VpdFile
):
1745 FvPath
= os
.path
.join(self
.BuildDir
, TAB_FV_DIRECTORY
)
1746 if not os
.path
.exists(FvPath
):
1750 EdkLogger
.error("build", FILE_WRITE_FAILURE
, "Fail to create FV folder under %s" % self
.BuildDir
)
1752 VpdFilePath
= os
.path
.join(FvPath
, "%s.txt" % self
.Platform
.VpdToolGuid
)
1754 if VpdFile
.Write(VpdFilePath
):
1755 # retrieve BPDG tool's path from tool_def.txt according to VPD_TOOL_GUID defined in DSC file.
1757 for ToolDef
in self
.ToolDefinition
.values():
1758 if TAB_GUID
in ToolDef
and ToolDef
[TAB_GUID
] == self
.Platform
.VpdToolGuid
:
1759 if "PATH" not in ToolDef
:
1760 EdkLogger
.error("build", ATTRIBUTE_NOT_AVAILABLE
, "PATH attribute was not provided for BPDG guid tool %s in tools_def.txt" % self
.Platform
.VpdToolGuid
)
1761 BPDGToolName
= ToolDef
["PATH"]
1763 # Call third party GUID BPDG tool.
1764 if BPDGToolName
is not None:
1765 VpdInfoFile
.CallExtenalBPDGTool(BPDGToolName
, VpdFilePath
)
1767 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.")
1769 ## Return the platform build data object
1772 return self
.BuildDatabase
[self
.MetaFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1774 ## Return platform name
1777 return self
.Platform
.PlatformName
1779 ## Return the meta file GUID
1782 return self
.Platform
.Guid
1784 ## Return the platform version
1787 return self
.Platform
.Version
1789 ## Return the FDF file name
1792 if self
.Workspace
.FdfFile
:
1793 RetVal
= mws
.join(self
.WorkspaceDir
, self
.Workspace
.FdfFile
)
1798 ## Return the build output directory platform specifies
1800 def OutputDir(self
):
1801 return self
.Platform
.OutputDirectory
1803 ## Return the directory to store all intermediate and final files built
1806 if os
.path
.isabs(self
.OutputDir
):
1807 GlobalData
.gBuildDirectory
= RetVal
= path
.join(
1808 path
.abspath(self
.OutputDir
),
1809 self
.BuildTarget
+ "_" + self
.ToolChain
,
1812 GlobalData
.gBuildDirectory
= RetVal
= path
.join(
1815 self
.BuildTarget
+ "_" + self
.ToolChain
,
1819 ## Return directory of platform makefile
1821 # @retval string Makefile directory
1824 def MakeFileDir(self
):
1825 return path
.join(self
.BuildDir
, self
.Arch
)
1827 ## Return build command string
1829 # @retval string Build command string
1832 def BuildCommand(self
):
1834 if "MAKE" in self
.ToolDefinition
and "PATH" in self
.ToolDefinition
["MAKE"]:
1835 RetVal
+= _SplitOption(self
.ToolDefinition
["MAKE"]["PATH"])
1836 if "FLAGS" in self
.ToolDefinition
["MAKE"]:
1837 NewOption
= self
.ToolDefinition
["MAKE"]["FLAGS"].strip()
1839 RetVal
+= _SplitOption(NewOption
)
1840 if "MAKE" in self
.EdkIIBuildOption
:
1841 if "FLAGS" in self
.EdkIIBuildOption
["MAKE"]:
1842 Flags
= self
.EdkIIBuildOption
["MAKE"]["FLAGS"]
1843 if Flags
.startswith('='):
1844 RetVal
= [RetVal
[0]] + [Flags
[1:]]
1846 RetVal
.append(Flags
)
1849 ## Get tool chain definition
1851 # Get each tool defition for given tool chain from tools_def.txt and platform
1854 def ToolDefinition(self
):
1855 ToolDefinition
= self
.Workspace
.ToolDef
.ToolsDefTxtDictionary
1856 if TAB_TOD_DEFINES_COMMAND_TYPE
not in self
.Workspace
.ToolDef
.ToolsDefTxtDatabase
:
1857 EdkLogger
.error('build', RESOURCE_NOT_AVAILABLE
, "No tools found in configuration",
1858 ExtraData
="[%s]" % self
.MetaFile
)
1861 for Def
in ToolDefinition
:
1862 Target
, Tag
, Arch
, Tool
, Attr
= Def
.split("_")
1863 if Target
!= self
.BuildTarget
or Tag
!= self
.ToolChain
or Arch
!= self
.Arch
:
1866 Value
= ToolDefinition
[Def
]
1867 # don't record the DLL
1869 DllPathList
.add(Value
)
1872 if Tool
not in RetVal
:
1874 RetVal
[Tool
][Attr
] = Value
1877 if GlobalData
.gOptions
.SilentMode
and "MAKE" in RetVal
:
1878 if "FLAGS" not in RetVal
["MAKE"]:
1879 RetVal
["MAKE"]["FLAGS"] = ""
1880 RetVal
["MAKE"]["FLAGS"] += " -s"
1883 for Attr
in RetVal
[Tool
]:
1884 Value
= RetVal
[Tool
][Attr
]
1885 if Tool
in self
._BuildOptionWithToolDef
(RetVal
) and Attr
in self
._BuildOptionWithToolDef
(RetVal
)[Tool
]:
1886 # check if override is indicated
1887 if self
._BuildOptionWithToolDef
(RetVal
)[Tool
][Attr
].startswith('='):
1888 Value
= self
._BuildOptionWithToolDef
(RetVal
)[Tool
][Attr
][1:]
1891 Value
+= " " + self
._BuildOptionWithToolDef
(RetVal
)[Tool
][Attr
]
1893 Value
= self
._BuildOptionWithToolDef
(RetVal
)[Tool
][Attr
]
1896 # Don't put MAKE definition in the file
1898 ToolsDef
+= "%s = %s\n" % (Tool
, Value
)
1900 # Don't put MAKE definition in the file
1905 ToolsDef
+= "%s_%s = %s\n" % (Tool
, Attr
, Value
)
1908 SaveFileOnChange(self
.ToolDefinitionFile
, ToolsDef
)
1909 for DllPath
in DllPathList
:
1910 os
.environ
["PATH"] = DllPath
+ os
.pathsep
+ os
.environ
["PATH"]
1911 os
.environ
["MAKE_FLAGS"] = MakeFlags
1915 ## Return the paths of tools
1917 def ToolDefinitionFile(self
):
1918 return os
.path
.join(self
.MakeFileDir
, "TOOLS_DEF." + self
.Arch
)
1920 ## Retrieve the toolchain family of given toolchain tag. Default to 'MSFT'.
1922 def ToolChainFamily(self
):
1923 ToolDefinition
= self
.Workspace
.ToolDef
.ToolsDefTxtDatabase
1924 if TAB_TOD_DEFINES_FAMILY
not in ToolDefinition \
1925 or self
.ToolChain
not in ToolDefinition
[TAB_TOD_DEFINES_FAMILY
] \
1926 or not ToolDefinition
[TAB_TOD_DEFINES_FAMILY
][self
.ToolChain
]:
1927 EdkLogger
.verbose("No tool chain family found in configuration for %s. Default to MSFT." \
1929 RetVal
= TAB_COMPILER_MSFT
1931 RetVal
= ToolDefinition
[TAB_TOD_DEFINES_FAMILY
][self
.ToolChain
]
1935 def BuildRuleFamily(self
):
1936 ToolDefinition
= self
.Workspace
.ToolDef
.ToolsDefTxtDatabase
1937 if TAB_TOD_DEFINES_BUILDRULEFAMILY
not in ToolDefinition \
1938 or self
.ToolChain
not in ToolDefinition
[TAB_TOD_DEFINES_BUILDRULEFAMILY
] \
1939 or not ToolDefinition
[TAB_TOD_DEFINES_BUILDRULEFAMILY
][self
.ToolChain
]:
1940 EdkLogger
.verbose("No tool chain family found in configuration for %s. Default to MSFT." \
1942 return TAB_COMPILER_MSFT
1944 return ToolDefinition
[TAB_TOD_DEFINES_BUILDRULEFAMILY
][self
.ToolChain
]
1946 ## Return the build options specific for all modules in this platform
1948 def BuildOption(self
):
1949 return self
._ExpandBuildOption
(self
.Platform
.BuildOptions
)
1951 def _BuildOptionWithToolDef(self
, ToolDef
):
1952 return self
._ExpandBuildOption
(self
.Platform
.BuildOptions
, ToolDef
=ToolDef
)
1954 ## Return the build options specific for EDK modules in this platform
1956 def EdkBuildOption(self
):
1957 return self
._ExpandBuildOption
(self
.Platform
.BuildOptions
, EDK_NAME
)
1959 ## Return the build options specific for EDKII modules in this platform
1961 def EdkIIBuildOption(self
):
1962 return self
._ExpandBuildOption
(self
.Platform
.BuildOptions
, EDKII_NAME
)
1964 ## Parse build_rule.txt in Conf Directory.
1966 # @retval BuildRule object
1969 def BuildRule(self
):
1970 BuildRuleFile
= None
1971 if TAB_TAT_DEFINES_BUILD_RULE_CONF
in self
.Workspace
.TargetTxt
.TargetTxtDictionary
:
1972 BuildRuleFile
= self
.Workspace
.TargetTxt
.TargetTxtDictionary
[TAB_TAT_DEFINES_BUILD_RULE_CONF
]
1973 if not BuildRuleFile
:
1974 BuildRuleFile
= gDefaultBuildRuleFile
1975 RetVal
= BuildRule(BuildRuleFile
)
1976 if RetVal
._FileVersion
== "":
1977 RetVal
._FileVersion
= AutoGenReqBuildRuleVerNum
1979 if RetVal
._FileVersion
< AutoGenReqBuildRuleVerNum
:
1980 # If Build Rule's version is less than the version number required by the tools, halting the build.
1981 EdkLogger
.error("build", AUTOGEN_ERROR
,
1982 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])"\
1983 % (RetVal
._FileVersion
, AutoGenReqBuildRuleVerNum
))
1986 ## Summarize the packages used by modules in this platform
1988 def PackageList(self
):
1990 for La
in self
.LibraryAutoGenList
:
1991 RetVal
.update(La
.DependentPackageList
)
1992 for Ma
in self
.ModuleAutoGenList
:
1993 RetVal
.update(Ma
.DependentPackageList
)
1994 #Collect package set information from INF of FDF
1995 for ModuleFile
in self
._AsBuildModuleList
:
1996 if ModuleFile
in self
.Platform
.Modules
:
1998 ModuleData
= self
.BuildDatabase
[ModuleFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1999 RetVal
.update(ModuleData
.Packages
)
2003 def NonDynamicPcdDict(self
):
2004 return {(Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
):Pcd
for Pcd
in self
.NonDynamicPcdList
}
2006 ## Get list of non-dynamic PCDs
2008 def NonDynamicPcdList(self
):
2009 if not self
._NonDynamicPcdList
:
2010 self
.CollectPlatformDynamicPcds()
2011 return self
._NonDynamicPcdList
2013 ## Get list of dynamic PCDs
2015 def DynamicPcdList(self
):
2016 if not self
._DynamicPcdList
:
2017 self
.CollectPlatformDynamicPcds()
2018 return self
._DynamicPcdList
2020 ## Generate Token Number for all PCD
2022 def PcdTokenNumber(self
):
2023 RetVal
= OrderedDict()
2026 # Make the Dynamic and DynamicEx PCD use within different TokenNumber area.
2030 # TokenNumber 0 ~ 10
2032 # TokeNumber 11 ~ 20
2034 for Pcd
in self
.DynamicPcdList
:
2035 if Pcd
.Phase
== "PEI" and Pcd
.Type
in PCD_DYNAMIC_TYPE_SET
:
2036 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
2037 RetVal
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
2040 for Pcd
in self
.DynamicPcdList
:
2041 if Pcd
.Phase
== "PEI" and Pcd
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
2042 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
2043 RetVal
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
2046 for Pcd
in self
.DynamicPcdList
:
2047 if Pcd
.Phase
== "DXE" and Pcd
.Type
in PCD_DYNAMIC_TYPE_SET
:
2048 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
2049 RetVal
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
2052 for Pcd
in self
.DynamicPcdList
:
2053 if Pcd
.Phase
== "DXE" and Pcd
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
2054 EdkLogger
.debug(EdkLogger
.DEBUG_5
, "%s %s (%s) -> %d" % (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, Pcd
.Phase
, TokenNumber
))
2055 RetVal
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
2058 for Pcd
in self
.NonDynamicPcdList
:
2059 RetVal
[Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
] = TokenNumber
2065 for ModuleFile
in self
.Platform
.Modules
:
2074 self
.Platform
.Modules
[ModuleFile
].M
= Ma
2075 return [x
.M
for x
in self
.Platform
.Modules
.values()]
2077 ## Summarize ModuleAutoGen objects of all modules to be built for this platform
2079 def ModuleAutoGenList(self
):
2081 for Ma
in self
._MaList
:
2082 if Ma
not in RetVal
:
2086 ## Summarize ModuleAutoGen objects of all libraries to be built for this platform
2088 def LibraryAutoGenList(self
):
2090 for Ma
in self
._MaList
:
2091 for La
in Ma
.LibraryAutoGenList
:
2092 if La
not in RetVal
:
2094 if Ma
not in La
.ReferenceModules
:
2095 La
.ReferenceModules
.append(Ma
)
2098 ## Test if a module is supported by the platform
2100 # An error will be raised directly if the module or its arch is not supported
2101 # by the platform or current configuration
2103 def ValidModule(self
, Module
):
2104 return Module
in self
.Platform
.Modules
or Module
in self
.Platform
.LibraryInstances \
2105 or Module
in self
._AsBuildModuleList
2107 ## Resolve the library classes in a module to library instances
2109 # This method will not only resolve library classes but also sort the library
2110 # instances according to the dependency-ship.
2112 # @param Module The module from which the library classes will be resolved
2114 # @retval library_list List of library instances sorted
2116 def ApplyLibraryInstance(self
, Module
):
2117 # Cover the case that the binary INF file is list in the FDF file but not DSC file, return empty list directly
2118 if str(Module
) not in self
.Platform
.Modules
:
2121 return GetModuleLibInstances(Module
,
2130 ## Override PCD setting (type, value, ...)
2132 # @param ToPcd The PCD to be overrided
2133 # @param FromPcd The PCD overrideing from
2135 def _OverridePcd(self
, ToPcd
, FromPcd
, Module
="", Msg
="", Library
=""):
2137 # in case there's PCDs coming from FDF file, which have no type given.
2138 # at this point, ToPcd.Type has the type found from dependent
2141 TokenCName
= ToPcd
.TokenCName
2142 for PcdItem
in GlobalData
.MixedPcd
:
2143 if (ToPcd
.TokenCName
, ToPcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
2144 TokenCName
= PcdItem
[0]
2146 if FromPcd
is not None:
2147 if ToPcd
.Pending
and FromPcd
.Type
:
2148 ToPcd
.Type
= FromPcd
.Type
2149 elif ToPcd
.Type
and FromPcd
.Type\
2150 and ToPcd
.Type
!= FromPcd
.Type
and ToPcd
.Type
in FromPcd
.Type
:
2151 if ToPcd
.Type
.strip() == TAB_PCDS_DYNAMIC_EX
:
2152 ToPcd
.Type
= FromPcd
.Type
2153 elif ToPcd
.Type
and FromPcd
.Type \
2154 and ToPcd
.Type
!= FromPcd
.Type
:
2156 Module
= str(Module
) + " 's library file (" + str(Library
) + ")"
2157 EdkLogger
.error("build", OPTION_CONFLICT
, "Mismatched PCD type",
2158 ExtraData
="%s.%s is used as [%s] in module %s, but as [%s] in %s."\
2159 % (ToPcd
.TokenSpaceGuidCName
, TokenCName
,
2160 ToPcd
.Type
, Module
, FromPcd
.Type
, Msg
),
2163 if FromPcd
.MaxDatumSize
:
2164 ToPcd
.MaxDatumSize
= FromPcd
.MaxDatumSize
2165 ToPcd
.MaxSizeUserSet
= FromPcd
.MaxDatumSize
2166 if FromPcd
.DefaultValue
:
2167 ToPcd
.DefaultValue
= FromPcd
.DefaultValue
2168 if FromPcd
.TokenValue
:
2169 ToPcd
.TokenValue
= FromPcd
.TokenValue
2170 if FromPcd
.DatumType
:
2171 ToPcd
.DatumType
= FromPcd
.DatumType
2172 if FromPcd
.SkuInfoList
:
2173 ToPcd
.SkuInfoList
= FromPcd
.SkuInfoList
2174 if FromPcd
.UserDefinedDefaultStoresFlag
:
2175 ToPcd
.UserDefinedDefaultStoresFlag
= FromPcd
.UserDefinedDefaultStoresFlag
2176 # Add Flexible PCD format parse
2177 if ToPcd
.DefaultValue
:
2179 ToPcd
.DefaultValue
= ValueExpressionEx(ToPcd
.DefaultValue
, ToPcd
.DatumType
, self
.Workspace
._GuidDict
)(True)
2180 except BadExpression
as Value
:
2181 EdkLogger
.error('Parser', FORMAT_INVALID
, 'PCD [%s.%s] Value "%s", %s' %(ToPcd
.TokenSpaceGuidCName
, ToPcd
.TokenCName
, ToPcd
.DefaultValue
, Value
),
2184 # check the validation of datum
2185 IsValid
, Cause
= CheckPcdDatum(ToPcd
.DatumType
, ToPcd
.DefaultValue
)
2187 EdkLogger
.error('build', FORMAT_INVALID
, Cause
, File
=self
.MetaFile
,
2188 ExtraData
="%s.%s" % (ToPcd
.TokenSpaceGuidCName
, TokenCName
))
2189 ToPcd
.validateranges
= FromPcd
.validateranges
2190 ToPcd
.validlists
= FromPcd
.validlists
2191 ToPcd
.expressions
= FromPcd
.expressions
2192 ToPcd
.CustomAttribute
= FromPcd
.CustomAttribute
2194 if FromPcd
is not None and ToPcd
.DatumType
== TAB_VOID
and not ToPcd
.MaxDatumSize
:
2195 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "No MaxDatumSize specified for PCD %s.%s" \
2196 % (ToPcd
.TokenSpaceGuidCName
, TokenCName
))
2197 Value
= ToPcd
.DefaultValue
2199 ToPcd
.MaxDatumSize
= '1'
2200 elif Value
[0] == 'L':
2201 ToPcd
.MaxDatumSize
= str((len(Value
) - 2) * 2)
2202 elif Value
[0] == '{':
2203 ToPcd
.MaxDatumSize
= str(len(Value
.split(',')))
2205 ToPcd
.MaxDatumSize
= str(len(Value
) - 1)
2207 # apply default SKU for dynamic PCDS if specified one is not available
2208 if (ToPcd
.Type
in PCD_DYNAMIC_TYPE_SET
or ToPcd
.Type
in PCD_DYNAMIC_EX_TYPE_SET
) \
2209 and not ToPcd
.SkuInfoList
:
2210 if self
.Platform
.SkuName
in self
.Platform
.SkuIds
:
2211 SkuName
= self
.Platform
.SkuName
2213 SkuName
= TAB_DEFAULT
2214 ToPcd
.SkuInfoList
= {
2215 SkuName
: SkuInfoClass(SkuName
, self
.Platform
.SkuIds
[SkuName
][0], '', '', '', '', '', ToPcd
.DefaultValue
)
2218 ## Apply PCD setting defined platform to a module
2220 # @param Module The module from which the PCD setting will be overrided
2222 # @retval PCD_list The list PCDs with settings from platform
2224 def ApplyPcdSetting(self
, Module
, Pcds
, Library
=""):
2225 # for each PCD in module
2226 for Name
, Guid
in Pcds
:
2227 PcdInModule
= Pcds
[Name
, Guid
]
2228 # find out the PCD setting in platform
2229 if (Name
, Guid
) in self
.Platform
.Pcds
:
2230 PcdInPlatform
= self
.Platform
.Pcds
[Name
, Guid
]
2232 PcdInPlatform
= None
2233 # then override the settings if any
2234 self
._OverridePcd
(PcdInModule
, PcdInPlatform
, Module
, Msg
="DSC PCD sections", Library
=Library
)
2235 # resolve the VariableGuid value
2236 for SkuId
in PcdInModule
.SkuInfoList
:
2237 Sku
= PcdInModule
.SkuInfoList
[SkuId
]
2238 if Sku
.VariableGuid
== '': continue
2239 Sku
.VariableGuidValue
= GuidValue(Sku
.VariableGuid
, self
.PackageList
, self
.MetaFile
.Path
)
2240 if Sku
.VariableGuidValue
is None:
2241 PackageList
= "\n\t".join(str(P
) for P
in self
.PackageList
)
2244 RESOURCE_NOT_AVAILABLE
,
2245 "Value of GUID [%s] is not found in" % Sku
.VariableGuid
,
2246 ExtraData
=PackageList
+ "\n\t(used with %s.%s from module %s)" \
2247 % (Guid
, Name
, str(Module
)),
2251 # override PCD settings with module specific setting
2252 if Module
in self
.Platform
.Modules
:
2253 PlatformModule
= self
.Platform
.Modules
[str(Module
)]
2254 for Key
in PlatformModule
.Pcds
:
2255 if GlobalData
.BuildOptionPcd
:
2256 for pcd
in GlobalData
.BuildOptionPcd
:
2257 (TokenSpaceGuidCName
, TokenCName
, FieldName
, pcdvalue
, _
) = pcd
2258 if (TokenCName
, TokenSpaceGuidCName
) == Key
and FieldName
=="":
2259 PlatformModule
.Pcds
[Key
].DefaultValue
= pcdvalue
2260 PlatformModule
.Pcds
[Key
].PcdValueFromComm
= pcdvalue
2266 elif Key
in GlobalData
.MixedPcd
:
2267 for PcdItem
in GlobalData
.MixedPcd
[Key
]:
2269 ToPcd
= Pcds
[PcdItem
]
2273 self
._OverridePcd
(ToPcd
, PlatformModule
.Pcds
[Key
], Module
, Msg
="DSC Components Module scoped PCD section", Library
=Library
)
2274 # use PCD value to calculate the MaxDatumSize when it is not specified
2275 for Name
, Guid
in Pcds
:
2276 Pcd
= Pcds
[Name
, Guid
]
2277 if Pcd
.DatumType
== TAB_VOID
and not Pcd
.MaxDatumSize
:
2278 Pcd
.MaxSizeUserSet
= None
2279 Value
= Pcd
.DefaultValue
2281 Pcd
.MaxDatumSize
= '1'
2282 elif Value
[0] == 'L':
2283 Pcd
.MaxDatumSize
= str((len(Value
) - 2) * 2)
2284 elif Value
[0] == '{':
2285 Pcd
.MaxDatumSize
= str(len(Value
.split(',')))
2287 Pcd
.MaxDatumSize
= str(len(Value
) - 1)
2288 return Pcds
.values()
2292 ## Calculate the priority value of the build option
2294 # @param Key Build option definition contain: TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
2296 # @retval Value Priority value based on the priority list.
2298 def CalculatePriorityValue(self
, Key
):
2299 Target
, ToolChain
, Arch
, CommandType
, Attr
= Key
.split('_')
2300 PriorityValue
= 0x11111
2301 if Target
== TAB_STAR
:
2302 PriorityValue
&= 0x01111
2303 if ToolChain
== TAB_STAR
:
2304 PriorityValue
&= 0x10111
2305 if Arch
== TAB_STAR
:
2306 PriorityValue
&= 0x11011
2307 if CommandType
== TAB_STAR
:
2308 PriorityValue
&= 0x11101
2309 if Attr
== TAB_STAR
:
2310 PriorityValue
&= 0x11110
2312 return self
.PrioList
["0x%0.5x" % PriorityValue
]
2315 ## Expand * in build option key
2317 # @param Options Options to be expanded
2318 # @param ToolDef Use specified ToolDef instead of full version.
2319 # This is needed during initialization to prevent
2320 # infinite recursion betweeh BuildOptions,
2321 # ToolDefinition, and this function.
2323 # @retval options Options expanded
2325 def _ExpandBuildOption(self
, Options
, ModuleStyle
=None, ToolDef
=None):
2327 ToolDef
= self
.ToolDefinition
2334 # Construct a list contain the build options which need override.
2338 # Key[0] -- tool family
2339 # Key[1] -- TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
2341 if (Key
[0] == self
.BuildRuleFamily
and
2342 (ModuleStyle
is None or len(Key
) < 3 or (len(Key
) > 2 and Key
[2] == ModuleStyle
))):
2343 Target
, ToolChain
, Arch
, CommandType
, Attr
= Key
[1].split('_')
2344 if (Target
== self
.BuildTarget
or Target
== TAB_STAR
) and\
2345 (ToolChain
== self
.ToolChain
or ToolChain
== TAB_STAR
) and\
2346 (Arch
== self
.Arch
or Arch
== TAB_STAR
) and\
2347 Options
[Key
].startswith("="):
2349 if OverrideList
.get(Key
[1]) is not None:
2350 OverrideList
.pop(Key
[1])
2351 OverrideList
[Key
[1]] = Options
[Key
]
2354 # Use the highest priority value.
2356 if (len(OverrideList
) >= 2):
2357 KeyList
= OverrideList
.keys()
2358 for Index
in range(len(KeyList
)):
2359 NowKey
= KeyList
[Index
]
2360 Target1
, ToolChain1
, Arch1
, CommandType1
, Attr1
= NowKey
.split("_")
2361 for Index1
in range(len(KeyList
) - Index
- 1):
2362 NextKey
= KeyList
[Index1
+ Index
+ 1]
2364 # Compare two Key, if one is included by another, choose the higher priority one
2366 Target2
, ToolChain2
, Arch2
, CommandType2
, Attr2
= NextKey
.split("_")
2367 if (Target1
== Target2
or Target1
== TAB_STAR
or Target2
== TAB_STAR
) and\
2368 (ToolChain1
== ToolChain2
or ToolChain1
== TAB_STAR
or ToolChain2
== TAB_STAR
) and\
2369 (Arch1
== Arch2
or Arch1
== TAB_STAR
or Arch2
== TAB_STAR
) and\
2370 (CommandType1
== CommandType2
or CommandType1
== TAB_STAR
or CommandType2
== TAB_STAR
) and\
2371 (Attr1
== Attr2
or Attr1
== TAB_STAR
or Attr2
== TAB_STAR
):
2373 if self
.CalculatePriorityValue(NowKey
) > self
.CalculatePriorityValue(NextKey
):
2374 if Options
.get((self
.BuildRuleFamily
, NextKey
)) is not None:
2375 Options
.pop((self
.BuildRuleFamily
, NextKey
))
2377 if Options
.get((self
.BuildRuleFamily
, NowKey
)) is not None:
2378 Options
.pop((self
.BuildRuleFamily
, NowKey
))
2381 if ModuleStyle
is not 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
in ToolDef
and Family
!= "":
2392 FamilyIsNull
= False
2393 if ToolDef
[Tool
].get(TAB_TOD_DEFINES_BUILDRULEFAMILY
, "") != "":
2394 if Family
!= ToolDef
[Tool
][TAB_TOD_DEFINES_BUILDRULEFAMILY
]:
2396 elif Family
!= ToolDef
[Tool
][TAB_TOD_DEFINES_FAMILY
]:
2399 # expand any wildcard
2400 if Target
== TAB_STAR
or Target
== self
.BuildTarget
:
2401 if Tag
== TAB_STAR
or Tag
== self
.ToolChain
:
2402 if Arch
== TAB_STAR
or Arch
== self
.Arch
:
2403 if Tool
not in BuildOptions
:
2404 BuildOptions
[Tool
] = {}
2405 if Attr
!= "FLAGS" or Attr
not in BuildOptions
[Tool
] or Options
[Key
].startswith('='):
2406 BuildOptions
[Tool
][Attr
] = Options
[Key
]
2408 # append options for the same tool except PATH
2410 BuildOptions
[Tool
][Attr
] += " " + Options
[Key
]
2412 BuildOptions
[Tool
][Attr
] = Options
[Key
]
2413 # Build Option Family has been checked, which need't to be checked again for family.
2414 if FamilyMatch
or FamilyIsNull
:
2418 if ModuleStyle
is not None and len (Key
) > 2:
2419 # Check Module style is EDK or EDKII.
2420 # Only append build option for the matched style module.
2421 if ModuleStyle
== EDK_NAME
and Key
[2] != EDK_NAME
:
2423 elif ModuleStyle
== EDKII_NAME
and Key
[2] != EDKII_NAME
:
2426 Target
, Tag
, Arch
, Tool
, Attr
= Key
[1].split("_")
2427 # if tool chain family doesn't match, skip it
2428 if Tool
not in ToolDef
or Family
== "":
2430 # option has been added before
2431 if Family
!= ToolDef
[Tool
][TAB_TOD_DEFINES_FAMILY
]:
2434 # expand any wildcard
2435 if Target
== TAB_STAR
or Target
== self
.BuildTarget
:
2436 if Tag
== TAB_STAR
or Tag
== self
.ToolChain
:
2437 if Arch
== TAB_STAR
or Arch
== self
.Arch
:
2438 if Tool
not in BuildOptions
:
2439 BuildOptions
[Tool
] = {}
2440 if Attr
!= "FLAGS" or Attr
not in BuildOptions
[Tool
] or Options
[Key
].startswith('='):
2441 BuildOptions
[Tool
][Attr
] = Options
[Key
]
2443 # append options for the same tool except PATH
2445 BuildOptions
[Tool
][Attr
] += " " + Options
[Key
]
2447 BuildOptions
[Tool
][Attr
] = Options
[Key
]
2450 ## Append build options in platform to a module
2452 # @param Module The module to which the build options will be appened
2454 # @retval options The options appended with build options in platform
2456 def ApplyBuildOption(self
, Module
):
2457 # Get the different options for the different style module
2458 PlatformOptions
= self
.EdkIIBuildOption
2459 ModuleTypeOptions
= self
.Platform
.GetBuildOptionsByModuleType(EDKII_NAME
, Module
.ModuleType
)
2460 ModuleTypeOptions
= self
._ExpandBuildOption
(ModuleTypeOptions
)
2461 ModuleOptions
= self
._ExpandBuildOption
(Module
.BuildOptions
)
2462 if Module
in self
.Platform
.Modules
:
2463 PlatformModule
= self
.Platform
.Modules
[str(Module
)]
2464 PlatformModuleOptions
= self
._ExpandBuildOption
(PlatformModule
.BuildOptions
)
2466 PlatformModuleOptions
= {}
2468 BuildRuleOrder
= None
2469 for Options
in [self
.ToolDefinition
, ModuleOptions
, PlatformOptions
, ModuleTypeOptions
, PlatformModuleOptions
]:
2470 for Tool
in Options
:
2471 for Attr
in Options
[Tool
]:
2472 if Attr
== TAB_TOD_DEFINES_BUILDRULEORDER
:
2473 BuildRuleOrder
= Options
[Tool
][Attr
]
2475 AllTools
= set(ModuleOptions
.keys() + PlatformOptions
.keys() +
2476 PlatformModuleOptions
.keys() + ModuleTypeOptions
.keys() +
2477 self
.ToolDefinition
.keys())
2478 BuildOptions
= defaultdict(lambda: defaultdict(str))
2479 for Tool
in AllTools
:
2480 for Options
in [self
.ToolDefinition
, ModuleOptions
, PlatformOptions
, ModuleTypeOptions
, PlatformModuleOptions
]:
2481 if Tool
not in Options
:
2483 for Attr
in Options
[Tool
]:
2485 # Do not generate it in Makefile
2487 if Attr
== TAB_TOD_DEFINES_BUILDRULEORDER
:
2489 Value
= Options
[Tool
][Attr
]
2490 # check if override is indicated
2491 if Value
.startswith('='):
2492 BuildOptions
[Tool
][Attr
] = mws
.handleWsMacro(Value
[1:])
2495 BuildOptions
[Tool
][Attr
] += " " + mws
.handleWsMacro(Value
)
2497 BuildOptions
[Tool
][Attr
] = mws
.handleWsMacro(Value
)
2499 return BuildOptions
, BuildRuleOrder
2502 # extend lists contained in a dictionary with lists stored in another dictionary
2503 # if CopyToDict is not derived from DefaultDict(list) then this may raise exception
2505 def ExtendCopyDictionaryLists(CopyToDict
, CopyFromDict
):
2506 for Key
in CopyFromDict
:
2507 CopyToDict
[Key
].extend(CopyFromDict
[Key
])
2509 # Create a directory specified by a set of path elements and return the full path
2510 def _MakeDir(PathList
):
2511 RetVal
= path
.join(*PathList
)
2512 CreateDirectory(RetVal
)
2515 ## ModuleAutoGen class
2517 # This class encapsules the AutoGen behaviors for the build tools. In addition to
2518 # the generation of AutoGen.h and AutoGen.c, it will generate *.depex file according
2519 # to the [depex] section in module's inf file.
2521 class ModuleAutoGen(AutoGen
):
2522 # call super().__init__ then call the worker function with different parameter count
2523 def __init__(self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
2524 if not hasattr(self
, "_Init"):
2525 self
._InitWorker
(Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
)
2528 ## Cache the timestamps of metafiles of every module in a class attribute
2532 def __new__(cls
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
2533 # check if this module is employed by active platform
2534 if not PlatformAutoGen(Workspace
, args
[0], Target
, Toolchain
, Arch
).ValidModule(MetaFile
):
2535 EdkLogger
.verbose("Module [%s] for [%s] is not employed by active platform\n" \
2538 return super(ModuleAutoGen
, cls
).__new
__(cls
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
)
2540 ## Initialize ModuleAutoGen
2542 # @param Workspace EdkIIWorkspaceBuild object
2543 # @param ModuleFile The path of module file
2544 # @param Target Build target (DEBUG, RELEASE)
2545 # @param Toolchain Name of tool chain
2546 # @param Arch The arch the module supports
2547 # @param PlatformFile Platform meta-file
2549 def _InitWorker(self
, Workspace
, ModuleFile
, Target
, Toolchain
, Arch
, PlatformFile
):
2550 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "AutoGen module [%s] [%s]" % (ModuleFile
, Arch
))
2551 GlobalData
.gProcessingFile
= "%s [%s, %s, %s]" % (ModuleFile
, Arch
, Toolchain
, Target
)
2553 self
.Workspace
= Workspace
2554 self
.WorkspaceDir
= Workspace
.WorkspaceDir
2555 self
.MetaFile
= ModuleFile
2556 self
.PlatformInfo
= PlatformAutoGen(Workspace
, PlatformFile
, Target
, Toolchain
, Arch
)
2558 self
.SourceDir
= self
.MetaFile
.SubDir
2559 self
.SourceDir
= mws
.relpath(self
.SourceDir
, self
.WorkspaceDir
)
2561 self
.SourceOverrideDir
= None
2562 # use overrided path defined in DSC file
2563 if self
.MetaFile
.Key
in GlobalData
.gOverrideDir
:
2564 self
.SourceOverrideDir
= GlobalData
.gOverrideDir
[self
.MetaFile
.Key
]
2566 self
.ToolChain
= Toolchain
2567 self
.BuildTarget
= Target
2569 self
.ToolChainFamily
= self
.PlatformInfo
.ToolChainFamily
2570 self
.BuildRuleFamily
= self
.PlatformInfo
.BuildRuleFamily
2572 self
.IsCodeFileCreated
= False
2573 self
.IsAsBuiltInfCreated
= False
2574 self
.DepexGenerated
= False
2576 self
.BuildDatabase
= self
.Workspace
.BuildDatabase
2577 self
.BuildRuleOrder
= None
2580 self
._PcdComments
= OrderedListDict()
2581 self
._GuidComments
= OrderedListDict()
2582 self
._ProtocolComments
= OrderedListDict()
2583 self
._PpiComments
= OrderedListDict()
2584 self
._BuildTargets
= None
2585 self
._IntroBuildTargetList
= None
2586 self
._FinalBuildTargetList
= None
2587 self
._FileTypes
= None
2589 self
.AutoGenDepSet
= set()
2590 self
.ReferenceModules
= []
2595 return "%s [%s]" % (self
.MetaFile
, self
.Arch
)
2597 # Get FixedAtBuild Pcds of this Module
2599 def FixedAtBuildPcds(self
):
2601 for Pcd
in self
.ModulePcdList
:
2602 if Pcd
.Type
!= TAB_PCDS_FIXED_AT_BUILD
:
2604 if Pcd
not in RetVal
:
2609 def FixedVoidTypePcds(self
):
2611 for Pcd
in self
.FixedAtBuildPcds
:
2612 if Pcd
.DatumType
== TAB_VOID
:
2613 if '{}.{}'.format(Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) not in RetVal
:
2614 RetVal
['{}.{}'.format(Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
)] = Pcd
.DefaultValue
2618 def UniqueBaseName(self
):
2619 BaseName
= self
.Name
2620 for Module
in self
.PlatformInfo
.ModuleAutoGenList
:
2621 if Module
.MetaFile
== self
.MetaFile
:
2623 if Module
.Name
== self
.Name
:
2624 if uuid
.UUID(Module
.Guid
) == uuid
.UUID(self
.Guid
):
2625 EdkLogger
.error("build", FILE_DUPLICATED
, 'Modules have same BaseName and FILE_GUID:\n'
2626 ' %s\n %s' % (Module
.MetaFile
, self
.MetaFile
))
2627 BaseName
= '%s_%s' % (self
.Name
, self
.Guid
)
2630 # Macros could be used in build_rule.txt (also Makefile)
2633 return OrderedDict((
2634 ("WORKSPACE" ,self
.WorkspaceDir
),
2635 ("MODULE_NAME" ,self
.Name
),
2636 ("MODULE_NAME_GUID" ,self
.UniqueBaseName
),
2637 ("MODULE_GUID" ,self
.Guid
),
2638 ("MODULE_VERSION" ,self
.Version
),
2639 ("MODULE_TYPE" ,self
.ModuleType
),
2640 ("MODULE_FILE" ,str(self
.MetaFile
)),
2641 ("MODULE_FILE_BASE_NAME" ,self
.MetaFile
.BaseName
),
2642 ("MODULE_RELATIVE_DIR" ,self
.SourceDir
),
2643 ("MODULE_DIR" ,self
.SourceDir
),
2644 ("BASE_NAME" ,self
.Name
),
2645 ("ARCH" ,self
.Arch
),
2646 ("TOOLCHAIN" ,self
.ToolChain
),
2647 ("TOOLCHAIN_TAG" ,self
.ToolChain
),
2648 ("TOOL_CHAIN_TAG" ,self
.ToolChain
),
2649 ("TARGET" ,self
.BuildTarget
),
2650 ("BUILD_DIR" ,self
.PlatformInfo
.BuildDir
),
2651 ("BIN_DIR" ,os
.path
.join(self
.PlatformInfo
.BuildDir
, self
.Arch
)),
2652 ("LIB_DIR" ,os
.path
.join(self
.PlatformInfo
.BuildDir
, self
.Arch
)),
2653 ("MODULE_BUILD_DIR" ,self
.BuildDir
),
2654 ("OUTPUT_DIR" ,self
.OutputDir
),
2655 ("DEBUG_DIR" ,self
.DebugDir
),
2656 ("DEST_DIR_OUTPUT" ,self
.OutputDir
),
2657 ("DEST_DIR_DEBUG" ,self
.DebugDir
),
2658 ("PLATFORM_NAME" ,self
.PlatformInfo
.Name
),
2659 ("PLATFORM_GUID" ,self
.PlatformInfo
.Guid
),
2660 ("PLATFORM_VERSION" ,self
.PlatformInfo
.Version
),
2661 ("PLATFORM_RELATIVE_DIR" ,self
.PlatformInfo
.SourceDir
),
2662 ("PLATFORM_DIR" ,mws
.join(self
.WorkspaceDir
, self
.PlatformInfo
.SourceDir
)),
2663 ("PLATFORM_OUTPUT_DIR" ,self
.PlatformInfo
.OutputDir
),
2664 ("FFS_OUTPUT_DIR" ,self
.FfsOutputDir
)
2667 ## Return the module build data object
2670 return self
.BuildDatabase
[self
.MetaFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
2672 ## Return the module name
2675 return self
.Module
.BaseName
2677 ## Return the module DxsFile if exist
2680 return self
.Module
.DxsFile
2682 ## Return the module meta-file GUID
2686 # To build same module more than once, the module path with FILE_GUID overridden has
2687 # the file name FILE_GUIDmodule.inf, but the relative path (self.MetaFile.File) is the realy path
2688 # in DSC. The overridden GUID can be retrieved from file name
2690 if os
.path
.basename(self
.MetaFile
.File
) != os
.path
.basename(self
.MetaFile
.Path
):
2692 # Length of GUID is 36
2694 return os
.path
.basename(self
.MetaFile
.Path
)[:36]
2695 return self
.Module
.Guid
2697 ## Return the module version
2700 return self
.Module
.Version
2702 ## Return the module type
2704 def ModuleType(self
):
2705 return self
.Module
.ModuleType
2707 ## Return the component type (for Edk.x style of module)
2709 def ComponentType(self
):
2710 return self
.Module
.ComponentType
2712 ## Return the build type
2714 def BuildType(self
):
2715 return self
.Module
.BuildType
2717 ## Return the PCD_IS_DRIVER setting
2719 def PcdIsDriver(self
):
2720 return self
.Module
.PcdIsDriver
2722 ## Return the autogen version, i.e. module meta-file version
2724 def AutoGenVersion(self
):
2725 return self
.Module
.AutoGenVersion
2727 ## Check if the module is library or not
2729 def IsLibrary(self
):
2730 return bool(self
.Module
.LibraryClass
)
2732 ## Check if the module is binary module or not
2734 def IsBinaryModule(self
):
2735 return self
.Module
.IsBinaryModule
2737 ## Return the directory to store intermediate files of the module
2741 self
.PlatformInfo
.BuildDir
,
2744 self
.MetaFile
.BaseName
2747 ## Return the directory to store the intermediate object files of the mdoule
2749 def OutputDir(self
):
2750 return _MakeDir((self
.BuildDir
, "OUTPUT"))
2752 ## Return the directory path to store ffs file
2754 def FfsOutputDir(self
):
2755 if GlobalData
.gFdfParser
:
2756 return path
.join(self
.PlatformInfo
.BuildDir
, TAB_FV_DIRECTORY
, "Ffs", self
.Guid
+ self
.Name
)
2759 ## Return the directory to store auto-gened source files of the mdoule
2762 return _MakeDir((self
.BuildDir
, "DEBUG"))
2764 ## Return the path of custom file
2766 def CustomMakefile(self
):
2768 for Type
in self
.Module
.CustomMakefile
:
2769 MakeType
= gMakeTypeMap
[Type
] if Type
in gMakeTypeMap
else 'nmake'
2770 if self
.SourceOverrideDir
is not None:
2771 File
= os
.path
.join(self
.SourceOverrideDir
, self
.Module
.CustomMakefile
[Type
])
2772 if not os
.path
.exists(File
):
2773 File
= os
.path
.join(self
.SourceDir
, self
.Module
.CustomMakefile
[Type
])
2775 File
= os
.path
.join(self
.SourceDir
, self
.Module
.CustomMakefile
[Type
])
2776 RetVal
[MakeType
] = File
2779 ## Return the directory of the makefile
2781 # @retval string The directory string of module's makefile
2784 def MakeFileDir(self
):
2785 return self
.BuildDir
2787 ## Return build command string
2789 # @retval string Build command string
2792 def BuildCommand(self
):
2793 return self
.PlatformInfo
.BuildCommand
2795 ## Get object list of all packages the module and its dependent libraries belong to
2797 # @retval list The list of package object
2800 def DerivedPackageList(self
):
2802 for M
in [self
.Module
] + self
.DependentLibraryList
:
2803 for Package
in M
.Packages
:
2804 if Package
in PackageList
:
2806 PackageList
.append(Package
)
2809 ## Get the depex string
2811 # @return : a string contain all depex expresion.
2812 def _GetDepexExpresionString(self
):
2815 ## DPX_SOURCE IN Define section.
2816 if self
.Module
.DxsFile
:
2818 for M
in [self
.Module
] + self
.DependentLibraryList
:
2819 Filename
= M
.MetaFile
.Path
2820 InfObj
= InfSectionParser
.InfSectionParser(Filename
)
2821 DepexExpresionList
= InfObj
.GetDepexExpresionList()
2822 for DepexExpresion
in DepexExpresionList
:
2823 for key
in DepexExpresion
:
2824 Arch
, ModuleType
= key
2825 DepexExpr
= [x
for x
in DepexExpresion
[key
] if not str(x
).startswith('#')]
2826 # the type of build module is USER_DEFINED.
2827 # All different DEPEX section tags would be copied into the As Built INF file
2828 # and there would be separate DEPEX section tags
2829 if self
.ModuleType
.upper() == SUP_MODULE_USER_DEFINED
:
2830 if (Arch
.upper() == self
.Arch
.upper()) and (ModuleType
.upper() != TAB_ARCH_COMMON
):
2831 DepexList
.append({(Arch
, ModuleType
): DepexExpr
})
2833 if Arch
.upper() == TAB_ARCH_COMMON
or \
2834 (Arch
.upper() == self
.Arch
.upper() and \
2835 ModuleType
.upper() in [TAB_ARCH_COMMON
, self
.ModuleType
.upper()]):
2836 DepexList
.append({(Arch
, ModuleType
): DepexExpr
})
2838 #the type of build module is USER_DEFINED.
2839 if self
.ModuleType
.upper() == SUP_MODULE_USER_DEFINED
:
2840 for Depex
in DepexList
:
2842 DepexStr
+= '[Depex.%s.%s]\n' % key
2843 DepexStr
+= '\n'.join('# '+ val
for val
in Depex
[key
])
2846 return '[Depex.%s]\n' % self
.Arch
2849 #the type of build module not is USER_DEFINED.
2851 for Depex
in DepexList
:
2856 for D
in Depex
.values():
2857 DepexStr
+= ' '.join(val
for val
in D
)
2858 Index
= DepexStr
.find('END')
2859 if Index
> -1 and Index
== len(DepexStr
) - 3:
2860 DepexStr
= DepexStr
[:-3]
2861 DepexStr
= DepexStr
.strip()
2864 DepexStr
= DepexStr
.lstrip('(').rstrip(')').strip()
2866 return '[Depex.%s]\n' % self
.Arch
2867 return '[Depex.%s]\n# ' % self
.Arch
+ DepexStr
2869 ## Merge dependency expression
2871 # @retval list The token list of the dependency expression after parsed
2874 def DepexList(self
):
2875 if self
.DxsFile
or self
.IsLibrary
or TAB_DEPENDENCY_EXPRESSION_FILE
in self
.FileTypes
:
2880 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion
2882 for M
in [self
.Module
] + self
.DependentLibraryList
:
2884 for D
in M
.Depex
[self
.Arch
, self
.ModuleType
]:
2886 DepexList
.append('AND')
2887 DepexList
.append('(')
2888 #replace D with value if D is FixedAtBuild PCD
2892 NewList
.append(item
)
2894 if item
not in self
.FixedVoidTypePcds
:
2895 EdkLogger
.error("build", FORMAT_INVALID
, "{} used in [Depex] section should be used as FixedAtBuild type and VOID* datum type in the module.".format(item
))
2897 Value
= self
.FixedVoidTypePcds
[item
]
2898 if len(Value
.split(',')) != 16:
2899 EdkLogger
.error("build", FORMAT_INVALID
,
2900 "{} used in [Depex] section should be used as FixedAtBuild type and VOID* datum type and 16 bytes in the module.".format(item
))
2901 NewList
.append(Value
)
2902 DepexList
.extend(NewList
)
2903 if DepexList
[-1] == 'END': # no need of a END at this time
2905 DepexList
.append(')')
2908 EdkLogger
.verbose("DEPEX[%s] (+%s) = %s" % (self
.Name
, M
.BaseName
, DepexList
))
2909 if 'BEFORE' in DepexList
or 'AFTER' in DepexList
:
2911 if len(DepexList
) > 0:
2912 EdkLogger
.verbose('')
2913 return {self
.ModuleType
:DepexList
}
2915 ## Merge dependency expression
2917 # @retval list The token list of the dependency expression after parsed
2920 def DepexExpressionDict(self
):
2921 if self
.DxsFile
or self
.IsLibrary
or TAB_DEPENDENCY_EXPRESSION_FILE
in self
.FileTypes
:
2924 DepexExpressionString
= ''
2926 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion
2928 for M
in [self
.Module
] + self
.DependentLibraryList
:
2930 for D
in M
.DepexExpression
[self
.Arch
, self
.ModuleType
]:
2931 if DepexExpressionString
!= '':
2932 DepexExpressionString
+= ' AND '
2933 DepexExpressionString
+= '('
2934 DepexExpressionString
+= D
2935 DepexExpressionString
= DepexExpressionString
.rstrip('END').strip()
2936 DepexExpressionString
+= ')'
2939 EdkLogger
.verbose("DEPEX[%s] (+%s) = %s" % (self
.Name
, M
.BaseName
, DepexExpressionString
))
2940 if 'BEFORE' in DepexExpressionString
or 'AFTER' in DepexExpressionString
:
2942 if len(DepexExpressionString
) > 0:
2943 EdkLogger
.verbose('')
2945 return {self
.ModuleType
:DepexExpressionString
}
2947 # Get the tiano core user extension, it is contain dependent library.
2948 # @retval: a list contain tiano core userextension.
2950 def _GetTianoCoreUserExtensionList(self
):
2951 TianoCoreUserExtentionList
= []
2952 for M
in [self
.Module
] + self
.DependentLibraryList
:
2953 Filename
= M
.MetaFile
.Path
2954 InfObj
= InfSectionParser
.InfSectionParser(Filename
)
2955 TianoCoreUserExtenList
= InfObj
.GetUserExtensionTianoCore()
2956 for TianoCoreUserExtent
in TianoCoreUserExtenList
:
2957 for Section
in TianoCoreUserExtent
:
2958 ItemList
= Section
.split(TAB_SPLIT
)
2960 if len(ItemList
) == 4:
2962 if Arch
.upper() == TAB_ARCH_COMMON
or Arch
.upper() == self
.Arch
.upper():
2964 TianoCoreList
.extend([TAB_SECTION_START
+ Section
+ TAB_SECTION_END
])
2965 TianoCoreList
.extend(TianoCoreUserExtent
[Section
][:])
2966 TianoCoreList
.append('\n')
2967 TianoCoreUserExtentionList
.append(TianoCoreList
)
2969 return TianoCoreUserExtentionList
2971 ## Return the list of specification version required for the module
2973 # @retval list The list of specification defined in module file
2976 def Specification(self
):
2977 return self
.Module
.Specification
2979 ## Tool option for the module build
2981 # @param PlatformInfo The object of PlatformBuildInfo
2982 # @retval dict The dict containing valid options
2985 def BuildOption(self
):
2986 RetVal
, self
.BuildRuleOrder
= self
.PlatformInfo
.ApplyBuildOption(self
.Module
)
2987 if self
.BuildRuleOrder
:
2988 self
.BuildRuleOrder
= ['.%s' % Ext
for Ext
in self
.BuildRuleOrder
.split()]
2991 ## Get include path list from tool option for the module build
2993 # @retval list The include path list
2996 def BuildOptionIncPathList(self
):
2998 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT
2999 # is the former use /I , the Latter used -I to specify include directories
3001 if self
.PlatformInfo
.ToolChainFamily
in (TAB_COMPILER_MSFT
):
3002 BuildOptIncludeRegEx
= gBuildOptIncludePatternMsft
3003 elif self
.PlatformInfo
.ToolChainFamily
in ('INTEL', 'GCC', 'RVCT'):
3004 BuildOptIncludeRegEx
= gBuildOptIncludePatternOther
3007 # New ToolChainFamily, don't known whether there is option to specify include directories
3012 for Tool
in ('CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'ASM'):
3014 FlagOption
= self
.BuildOption
[Tool
]['FLAGS']
3018 if self
.ToolChainFamily
!= 'RVCT':
3019 IncPathList
= [NormPath(Path
, self
.Macros
) for Path
in BuildOptIncludeRegEx
.findall(FlagOption
)]
3022 # RVCT may specify a list of directory seperated by commas
3025 for Path
in BuildOptIncludeRegEx
.findall(FlagOption
):
3026 PathList
= GetSplitList(Path
, TAB_COMMA_SPLIT
)
3027 IncPathList
.extend(NormPath(PathEntry
, self
.Macros
) for PathEntry
in PathList
)
3030 # EDK II modules must not reference header files outside of the packages they depend on or
3031 # within the module's directory tree. Report error if violation.
3033 for Path
in IncPathList
:
3034 if (Path
not in self
.IncludePathList
) and (CommonPath([Path
, self
.MetaFile
.Dir
]) != self
.MetaFile
.Dir
):
3035 ErrMsg
= "The include directory for the EDK II module in this line is invalid %s specified in %s FLAGS '%s'" % (Path
, Tool
, FlagOption
)
3036 EdkLogger
.error("build",
3039 File
=str(self
.MetaFile
))
3040 RetVal
+= IncPathList
3043 ## Return a list of files which can be built from source
3045 # What kind of files can be built is determined by build rules in
3046 # $(CONF_DIRECTORY)/build_rule.txt and toolchain family.
3049 def SourceFileList(self
):
3051 ToolChainTagSet
= {"", TAB_STAR
, self
.ToolChain
}
3052 ToolChainFamilySet
= {"", TAB_STAR
, self
.ToolChainFamily
, self
.BuildRuleFamily
}
3053 for F
in self
.Module
.Sources
:
3055 if F
.TagName
not in ToolChainTagSet
:
3056 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "The toolchain [%s] for processing file [%s] is found, "
3057 "but [%s] is currently used" % (F
.TagName
, str(F
), self
.ToolChain
))
3059 # match tool chain family or build rule family
3060 if F
.ToolChainFamily
not in ToolChainFamilySet
:
3063 "The file [%s] must be built by tools of [%s], " \
3064 "but current toolchain family is [%s], buildrule family is [%s]" \
3065 % (str(F
), F
.ToolChainFamily
, self
.ToolChainFamily
, self
.BuildRuleFamily
))
3068 # add the file path into search path list for file including
3069 if F
.Dir
not in self
.IncludePathList
:
3070 self
.IncludePathList
.insert(0, F
.Dir
)
3073 self
._MatchBuildRuleOrder
(RetVal
)
3076 self
._ApplyBuildRule
(F
, TAB_UNKNOWN_FILE
)
3079 def _MatchBuildRuleOrder(self
, FileList
):
3082 for SingleFile
in FileList
:
3083 if self
.BuildRuleOrder
and SingleFile
.Ext
in self
.BuildRuleOrder
and SingleFile
.Ext
in self
.BuildRules
:
3084 key
= SingleFile
.Path
.rsplit(SingleFile
.Ext
,1)[0]
3085 if key
in Order_Dict
:
3086 Order_Dict
[key
].append(SingleFile
.Ext
)
3088 Order_Dict
[key
] = [SingleFile
.Ext
]
3091 for F
in Order_Dict
:
3092 if len(Order_Dict
[F
]) > 1:
3093 Order_Dict
[F
].sort(key
=lambda i
: self
.BuildRuleOrder
.index(i
))
3094 for Ext
in Order_Dict
[F
][1:]:
3095 RemoveList
.append(F
+ Ext
)
3097 for item
in RemoveList
:
3098 FileList
.remove(item
)
3102 ## Return the list of unicode files
3104 def UnicodeFileList(self
):
3105 return self
.FileTypes
.get(TAB_UNICODE_FILE
,[])
3107 ## Return the list of vfr files
3109 def VfrFileList(self
):
3110 return self
.FileTypes
.get(TAB_VFR_FILE
, [])
3112 ## Return the list of Image Definition files
3114 def IdfFileList(self
):
3115 return self
.FileTypes
.get(TAB_IMAGE_FILE
,[])
3117 ## Return a list of files which can be built from binary
3119 # "Build" binary files are just to copy them to build directory.
3121 # @retval list The list of files which can be built later
3124 def BinaryFileList(self
):
3126 for F
in self
.Module
.Binaries
:
3127 if F
.Target
not in [TAB_ARCH_COMMON
, TAB_STAR
] and F
.Target
!= self
.BuildTarget
:
3130 self
._ApplyBuildRule
(F
, F
.Type
, BinaryFileList
=RetVal
)
3134 def BuildRules(self
):
3136 BuildRuleDatabase
= self
.PlatformInfo
.BuildRule
3137 for Type
in BuildRuleDatabase
.FileTypeList
:
3138 #first try getting build rule by BuildRuleFamily
3139 RuleObject
= BuildRuleDatabase
[Type
, self
.BuildType
, self
.Arch
, self
.BuildRuleFamily
]
3141 # build type is always module type, but ...
3142 if self
.ModuleType
!= self
.BuildType
:
3143 RuleObject
= BuildRuleDatabase
[Type
, self
.ModuleType
, self
.Arch
, self
.BuildRuleFamily
]
3144 #second try getting build rule by ToolChainFamily
3146 RuleObject
= BuildRuleDatabase
[Type
, self
.BuildType
, self
.Arch
, self
.ToolChainFamily
]
3148 # build type is always module type, but ...
3149 if self
.ModuleType
!= self
.BuildType
:
3150 RuleObject
= BuildRuleDatabase
[Type
, self
.ModuleType
, self
.Arch
, self
.ToolChainFamily
]
3153 RuleObject
= RuleObject
.Instantiate(self
.Macros
)
3154 RetVal
[Type
] = RuleObject
3155 for Ext
in RuleObject
.SourceFileExtList
:
3156 RetVal
[Ext
] = RuleObject
3159 def _ApplyBuildRule(self
, File
, FileType
, BinaryFileList
=None):
3160 if self
._BuildTargets
is None:
3161 self
._IntroBuildTargetList
= set()
3162 self
._FinalBuildTargetList
= set()
3163 self
._BuildTargets
= defaultdict(set)
3164 self
._FileTypes
= defaultdict(set)
3166 if not BinaryFileList
:
3167 BinaryFileList
= self
.BinaryFileList
3169 SubDirectory
= os
.path
.join(self
.OutputDir
, File
.SubDir
)
3170 if not os
.path
.exists(SubDirectory
):
3171 CreateDirectory(SubDirectory
)
3177 # Make sure to get build rule order value
3181 while Index
< len(SourceList
):
3182 Source
= SourceList
[Index
]
3186 CreateDirectory(Source
.Dir
)
3188 if File
.IsBinary
and File
== Source
and File
in BinaryFileList
:
3189 # Skip all files that are not binary libraries
3190 if not self
.IsLibrary
:
3192 RuleObject
= self
.BuildRules
[TAB_DEFAULT_BINARY_FILE
]
3193 elif FileType
in self
.BuildRules
:
3194 RuleObject
= self
.BuildRules
[FileType
]
3195 elif Source
.Ext
in self
.BuildRules
:
3196 RuleObject
= self
.BuildRules
[Source
.Ext
]
3198 # stop at no more rules
3200 self
._FinalBuildTargetList
.add(LastTarget
)
3203 FileType
= RuleObject
.SourceFileType
3204 self
._FileTypes
[FileType
].add(Source
)
3206 # stop at STATIC_LIBRARY for library
3207 if self
.IsLibrary
and FileType
== TAB_STATIC_LIBRARY
:
3209 self
._FinalBuildTargetList
.add(LastTarget
)
3212 Target
= RuleObject
.Apply(Source
, self
.BuildRuleOrder
)
3215 self
._FinalBuildTargetList
.add(LastTarget
)
3217 elif not Target
.Outputs
:
3218 # Only do build for target with outputs
3219 self
._FinalBuildTargetList
.add(Target
)
3221 self
._BuildTargets
[FileType
].add(Target
)
3223 if not Source
.IsBinary
and Source
== File
:
3224 self
._IntroBuildTargetList
.add(Target
)
3226 # to avoid cyclic rule
3227 if FileType
in RuleChain
:
3230 RuleChain
.add(FileType
)
3231 SourceList
.extend(Target
.Outputs
)
3233 FileType
= TAB_UNKNOWN_FILE
3237 if self
._BuildTargets
is None:
3238 self
._IntroBuildTargetList
= set()
3239 self
._FinalBuildTargetList
= set()
3240 self
._BuildTargets
= defaultdict(set)
3241 self
._FileTypes
= defaultdict(set)
3243 #TRICK: call SourceFileList property to apply build rule for source files
3246 #TRICK: call _GetBinaryFileList to apply build rule for binary files
3249 return self
._BuildTargets
3252 def IntroTargetList(self
):
3254 return self
._IntroBuildTargetList
3257 def CodaTargetList(self
):
3259 return self
._FinalBuildTargetList
3262 def FileTypes(self
):
3264 return self
._FileTypes
3266 ## Get the list of package object the module depends on
3268 # @retval list The package object list
3271 def DependentPackageList(self
):
3272 return self
.Module
.Packages
3274 ## Return the list of auto-generated code file
3276 # @retval list The list of auto-generated file
3279 def AutoGenFileList(self
):
3280 AutoGenUniIdf
= self
.BuildType
!= 'UEFI_HII'
3281 UniStringBinBuffer
= BytesIO()
3282 IdfGenBinBuffer
= BytesIO()
3284 AutoGenC
= TemplateString()
3285 AutoGenH
= TemplateString()
3286 StringH
= TemplateString()
3287 StringIdf
= TemplateString()
3288 GenC
.CreateCode(self
, AutoGenC
, AutoGenH
, StringH
, AutoGenUniIdf
, UniStringBinBuffer
, StringIdf
, AutoGenUniIdf
, IdfGenBinBuffer
)
3290 # AutoGen.c is generated if there are library classes in inf, or there are object files
3292 if str(AutoGenC
) != "" and (len(self
.Module
.LibraryClasses
) > 0
3293 or TAB_OBJECT_FILE
in self
.FileTypes
):
3294 AutoFile
= PathClass(gAutoGenCodeFileName
, self
.DebugDir
)
3295 RetVal
[AutoFile
] = str(AutoGenC
)
3296 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3297 if str(AutoGenH
) != "":
3298 AutoFile
= PathClass(gAutoGenHeaderFileName
, self
.DebugDir
)
3299 RetVal
[AutoFile
] = str(AutoGenH
)
3300 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3301 if str(StringH
) != "":
3302 AutoFile
= PathClass(gAutoGenStringFileName
% {"module_name":self
.Name
}, self
.DebugDir
)
3303 RetVal
[AutoFile
] = str(StringH
)
3304 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3305 if UniStringBinBuffer
is not None and UniStringBinBuffer
.getvalue() != "":
3306 AutoFile
= PathClass(gAutoGenStringFormFileName
% {"module_name":self
.Name
}, self
.OutputDir
)
3307 RetVal
[AutoFile
] = UniStringBinBuffer
.getvalue()
3308 AutoFile
.IsBinary
= True
3309 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3310 if UniStringBinBuffer
is not None:
3311 UniStringBinBuffer
.close()
3312 if str(StringIdf
) != "":
3313 AutoFile
= PathClass(gAutoGenImageDefFileName
% {"module_name":self
.Name
}, self
.DebugDir
)
3314 RetVal
[AutoFile
] = str(StringIdf
)
3315 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3316 if IdfGenBinBuffer
is not None and IdfGenBinBuffer
.getvalue() != "":
3317 AutoFile
= PathClass(gAutoGenIdfFileName
% {"module_name":self
.Name
}, self
.OutputDir
)
3318 RetVal
[AutoFile
] = IdfGenBinBuffer
.getvalue()
3319 AutoFile
.IsBinary
= True
3320 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
3321 if IdfGenBinBuffer
is not None:
3322 IdfGenBinBuffer
.close()
3325 ## Return the list of library modules explicitly or implicityly used by this module
3327 def DependentLibraryList(self
):
3328 # only merge library classes and PCD for non-library module
3331 return self
.PlatformInfo
.ApplyLibraryInstance(self
.Module
)
3333 ## Get the list of PCDs from current module
3335 # @retval list The list of PCD
3338 def ModulePcdList(self
):
3339 # apply PCD settings from platform
3340 RetVal
= self
.PlatformInfo
.ApplyPcdSetting(self
.Module
, self
.Module
.Pcds
)
3341 ExtendCopyDictionaryLists(self
._PcdComments
, self
.Module
.PcdComments
)
3344 ## Get the list of PCDs from dependent libraries
3346 # @retval list The list of PCD
3349 def LibraryPcdList(self
):
3354 # get PCDs from dependent libraries
3355 for Library
in self
.DependentLibraryList
:
3356 PcdsInLibrary
= OrderedDict()
3357 ExtendCopyDictionaryLists(self
._PcdComments
, Library
.PcdComments
)
3358 for Key
in Library
.Pcds
:
3359 # skip duplicated PCDs
3360 if Key
in self
.Module
.Pcds
or Key
in Pcds
:
3363 PcdsInLibrary
[Key
] = copy
.copy(Library
.Pcds
[Key
])
3364 RetVal
.extend(self
.PlatformInfo
.ApplyPcdSetting(self
.Module
, PcdsInLibrary
, Library
=Library
))
3367 ## Get the GUID value mapping
3369 # @retval dict The mapping between GUID cname and its value
3373 RetVal
= OrderedDict(self
.Module
.Guids
)
3374 for Library
in self
.DependentLibraryList
:
3375 RetVal
.update(Library
.Guids
)
3376 ExtendCopyDictionaryLists(self
._GuidComments
, Library
.GuidComments
)
3377 ExtendCopyDictionaryLists(self
._GuidComments
, self
.Module
.GuidComments
)
3381 def GetGuidsUsedByPcd(self
):
3382 RetVal
= OrderedDict(self
.Module
.GetGuidsUsedByPcd())
3383 for Library
in self
.DependentLibraryList
:
3384 RetVal
.update(Library
.GetGuidsUsedByPcd())
3386 ## Get the protocol value mapping
3388 # @retval dict The mapping between protocol cname and its value
3391 def ProtocolList(self
):
3392 RetVal
= OrderedDict(self
.Module
.Protocols
)
3393 for Library
in self
.DependentLibraryList
:
3394 RetVal
.update(Library
.Protocols
)
3395 ExtendCopyDictionaryLists(self
._ProtocolComments
, Library
.ProtocolComments
)
3396 ExtendCopyDictionaryLists(self
._ProtocolComments
, self
.Module
.ProtocolComments
)
3399 ## Get the PPI value mapping
3401 # @retval dict The mapping between PPI cname and its value
3405 RetVal
= OrderedDict(self
.Module
.Ppis
)
3406 for Library
in self
.DependentLibraryList
:
3407 RetVal
.update(Library
.Ppis
)
3408 ExtendCopyDictionaryLists(self
._PpiComments
, Library
.PpiComments
)
3409 ExtendCopyDictionaryLists(self
._PpiComments
, self
.Module
.PpiComments
)
3412 ## Get the list of include search path
3414 # @retval list The list path
3417 def IncludePathList(self
):
3419 RetVal
.append(self
.MetaFile
.Dir
)
3420 RetVal
.append(self
.DebugDir
)
3422 for Package
in self
.Module
.Packages
:
3423 PackageDir
= mws
.join(self
.WorkspaceDir
, Package
.MetaFile
.Dir
)
3424 if PackageDir
not in RetVal
:
3425 RetVal
.append(PackageDir
)
3426 IncludesList
= Package
.Includes
3427 if Package
._PrivateIncludes
:
3428 if not self
.MetaFile
.Path
.startswith(PackageDir
):
3429 IncludesList
= list(set(Package
.Includes
).difference(set(Package
._PrivateIncludes
)))
3430 for Inc
in IncludesList
:
3431 if Inc
not in RetVal
:
3432 RetVal
.append(str(Inc
))
3436 def IncludePathLength(self
):
3437 return sum(len(inc
)+1 for inc
in self
.IncludePathList
)
3439 ## Get HII EX PCDs which maybe used by VFR
3441 # efivarstore used by VFR may relate with HII EX PCDs
3442 # Get the variable name and GUID from efivarstore and HII EX PCD
3443 # List the HII EX PCDs in As Built INF if both name and GUID match.
3445 # @retval list HII EX PCDs
3447 def _GetPcdsMaybeUsedByVfr(self
):
3448 if not self
.SourceFileList
:
3452 for SrcFile
in self
.SourceFileList
:
3453 if SrcFile
.Ext
.lower() != '.vfr':
3455 Vfri
= os
.path
.join(self
.OutputDir
, SrcFile
.BaseName
+ '.i')
3456 if not os
.path
.exists(Vfri
):
3458 VfriFile
= open(Vfri
, 'r')
3459 Content
= VfriFile
.read()
3461 Pos
= Content
.find('efivarstore')
3464 # Make sure 'efivarstore' is the start of efivarstore statement
3465 # In case of the value of 'name' (name = efivarstore) is equal to 'efivarstore'
3468 while Index
>= 0 and Content
[Index
] in ' \t\r\n':
3470 if Index
>= 0 and Content
[Index
] != ';':
3471 Pos
= Content
.find('efivarstore', Pos
+ len('efivarstore'))
3474 # 'efivarstore' must be followed by name and guid
3476 Name
= gEfiVarStoreNamePattern
.search(Content
, Pos
)
3479 Guid
= gEfiVarStoreGuidPattern
.search(Content
, Pos
)
3482 NameArray
= _ConvertStringToByteArray('L"' + Name
.group(1) + '"')
3483 NameGuids
.add((NameArray
, GuidStructureStringToGuidString(Guid
.group(1))))
3484 Pos
= Content
.find('efivarstore', Name
.end())
3488 for Pcd
in self
.PlatformInfo
.Platform
.Pcds
.values():
3489 if Pcd
.Type
!= TAB_PCDS_DYNAMIC_EX_HII
:
3491 for SkuInfo
in Pcd
.SkuInfoList
.values():
3492 Value
= GuidValue(SkuInfo
.VariableGuid
, self
.PlatformInfo
.PackageList
, self
.MetaFile
.Path
)
3495 Name
= _ConvertStringToByteArray(SkuInfo
.VariableName
)
3496 Guid
= GuidStructureStringToGuidString(Value
)
3497 if (Name
, Guid
) in NameGuids
and Pcd
not in HiiExPcds
:
3498 HiiExPcds
.append(Pcd
)
3503 def _GenOffsetBin(self
):
3505 for SourceFile
in self
.Module
.Sources
:
3506 if SourceFile
.Type
.upper() == ".VFR" :
3508 # search the .map file to find the offset of vfr binary in the PE32+/TE file.
3510 VfrUniBaseName
[SourceFile
.BaseName
] = (SourceFile
.BaseName
+ "Bin")
3511 elif SourceFile
.Type
.upper() == ".UNI" :
3513 # search the .map file to find the offset of Uni strings binary in the PE32+/TE file.
3515 VfrUniBaseName
["UniOffsetName"] = (self
.Name
+ "Strings")
3517 if not VfrUniBaseName
:
3519 MapFileName
= os
.path
.join(self
.OutputDir
, self
.Name
+ ".map")
3520 EfiFileName
= os
.path
.join(self
.OutputDir
, self
.Name
+ ".efi")
3521 VfrUniOffsetList
= GetVariableOffset(MapFileName
, EfiFileName
, VfrUniBaseName
.values())
3522 if not VfrUniOffsetList
:
3525 OutputName
= '%sOffset.bin' % self
.Name
3526 UniVfrOffsetFileName
= os
.path
.join( self
.OutputDir
, OutputName
)
3529 fInputfile
= open(UniVfrOffsetFileName
, "wb+", 0)
3531 EdkLogger
.error("build", FILE_OPEN_FAILURE
, "File open failed for %s" % UniVfrOffsetFileName
, None)
3533 # Use a instance of BytesIO to cache data
3534 fStringIO
= BytesIO('')
3536 for Item
in VfrUniOffsetList
:
3537 if (Item
[0].find("Strings") != -1):
3539 # UNI offset in image.
3541 # { 0x8913c5e0, 0x33f6, 0x4d86, { 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66 } }
3543 UniGuid
= [0xe0, 0xc5, 0x13, 0x89, 0xf6, 0x33, 0x86, 0x4d, 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66]
3544 UniGuid
= [chr(ItemGuid
) for ItemGuid
in UniGuid
]
3545 fStringIO
.write(''.join(UniGuid
))
3546 UniValue
= pack ('Q', int (Item
[1], 16))
3547 fStringIO
.write (UniValue
)
3550 # VFR binary offset in image.
3552 # { 0xd0bc7cb4, 0x6a47, 0x495f, { 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2 } };
3554 VfrGuid
= [0xb4, 0x7c, 0xbc, 0xd0, 0x47, 0x6a, 0x5f, 0x49, 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2]
3555 VfrGuid
= [chr(ItemGuid
) for ItemGuid
in VfrGuid
]
3556 fStringIO
.write(''.join(VfrGuid
))
3557 VfrValue
= pack ('Q', int (Item
[1], 16))
3558 fStringIO
.write (VfrValue
)
3560 # write data into file.
3563 fInputfile
.write (fStringIO
.getvalue())
3565 EdkLogger
.error("build", FILE_WRITE_FAILURE
, "Write data to file %s failed, please check whether the "
3566 "file been locked or using by other applications." %UniVfrOffsetFileName
, None)
3572 ## Create AsBuilt INF file the module
3574 def CreateAsBuiltInf(self
, IsOnlyCopy
= False):
3575 self
.OutputFile
= set()
3576 if IsOnlyCopy
and GlobalData
.gBinCacheDest
:
3577 self
.CopyModuleToCache()
3580 if self
.IsAsBuiltInfCreated
:
3583 # Skip the following code for libraries
3587 # Skip the following code for modules with no source files
3588 if not self
.SourceFileList
:
3591 # Skip the following code for modules without any binary files
3592 if self
.BinaryFileList
:
3595 ### TODO: How to handles mixed source and binary modules
3597 # Find all DynamicEx and PatchableInModule PCDs used by this module and dependent libraries
3598 # Also find all packages that the DynamicEx PCDs depend on
3603 PcdTokenSpaceList
= []
3604 for Pcd
in self
.ModulePcdList
+ self
.LibraryPcdList
:
3605 if Pcd
.Type
== TAB_PCDS_PATCHABLE_IN_MODULE
:
3606 PatchablePcds
.append(Pcd
)
3607 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, TAB_PCDS_PATCHABLE_IN_MODULE
))
3608 elif Pcd
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
3611 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC_EX
))
3612 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC
))
3613 PcdTokenSpaceList
.append(Pcd
.TokenSpaceGuidCName
)
3614 GuidList
= OrderedDict(self
.GuidList
)
3615 for TokenSpace
in self
.GetGuidsUsedByPcd
:
3616 # If token space is not referred by patch PCD or Ex PCD, remove the GUID from GUID list
3617 # The GUIDs in GUIDs section should really be the GUIDs in source INF or referred by Ex an patch PCDs
3618 if TokenSpace
not in PcdTokenSpaceList
and TokenSpace
in GuidList
:
3619 GuidList
.pop(TokenSpace
)
3620 CheckList
= (GuidList
, self
.PpiList
, self
.ProtocolList
, PcdCheckList
)
3621 for Package
in self
.DerivedPackageList
:
3622 if Package
in Packages
:
3624 BeChecked
= (Package
.Guids
, Package
.Ppis
, Package
.Protocols
, Package
.Pcds
)
3626 for Index
in range(len(BeChecked
)):
3627 for Item
in CheckList
[Index
]:
3628 if Item
in BeChecked
[Index
]:
3629 Packages
.append(Package
)
3635 VfrPcds
= self
._GetPcdsMaybeUsedByVfr
()
3636 for Pkg
in self
.PlatformInfo
.PackageList
:
3639 for VfrPcd
in VfrPcds
:
3640 if ((VfrPcd
.TokenCName
, VfrPcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC_EX
) in Pkg
.Pcds
or
3641 (VfrPcd
.TokenCName
, VfrPcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC
) in Pkg
.Pcds
):
3642 Packages
.append(Pkg
)
3645 ModuleType
= SUP_MODULE_DXE_DRIVER
if self
.ModuleType
== SUP_MODULE_UEFI_DRIVER
and self
.DepexGenerated
else self
.ModuleType
3646 DriverType
= self
.PcdIsDriver
if self
.PcdIsDriver
else ''
3648 MDefs
= self
.Module
.Defines
3651 'module_name' : self
.Name
,
3652 'module_guid' : Guid
,
3653 'module_module_type' : ModuleType
,
3654 'module_version_string' : [MDefs
['VERSION_STRING']] if 'VERSION_STRING' in MDefs
else [],
3655 'pcd_is_driver_string' : [],
3656 'module_uefi_specification_version' : [],
3657 'module_pi_specification_version' : [],
3658 'module_entry_point' : self
.Module
.ModuleEntryPointList
,
3659 'module_unload_image' : self
.Module
.ModuleUnloadImageList
,
3660 'module_constructor' : self
.Module
.ConstructorList
,
3661 'module_destructor' : self
.Module
.DestructorList
,
3662 'module_shadow' : [MDefs
['SHADOW']] if 'SHADOW' in MDefs
else [],
3663 'module_pci_vendor_id' : [MDefs
['PCI_VENDOR_ID']] if 'PCI_VENDOR_ID' in MDefs
else [],
3664 'module_pci_device_id' : [MDefs
['PCI_DEVICE_ID']] if 'PCI_DEVICE_ID' in MDefs
else [],
3665 'module_pci_class_code' : [MDefs
['PCI_CLASS_CODE']] if 'PCI_CLASS_CODE' in MDefs
else [],
3666 'module_pci_revision' : [MDefs
['PCI_REVISION']] if 'PCI_REVISION' in MDefs
else [],
3667 'module_build_number' : [MDefs
['BUILD_NUMBER']] if 'BUILD_NUMBER' in MDefs
else [],
3668 'module_spec' : [MDefs
['SPEC']] if 'SPEC' in MDefs
else [],
3669 'module_uefi_hii_resource_section' : [MDefs
['UEFI_HII_RESOURCE_SECTION']] if 'UEFI_HII_RESOURCE_SECTION' in MDefs
else [],
3670 'module_uni_file' : [MDefs
['MODULE_UNI_FILE']] if 'MODULE_UNI_FILE' in MDefs
else [],
3671 'module_arch' : self
.Arch
,
3672 'package_item' : [Package
.MetaFile
.File
.replace('\\', '/') for Package
in Packages
],
3674 'patchablepcd_item' : [],
3676 'protocol_item' : [],
3680 'libraryclasses_item' : []
3683 if 'MODULE_UNI_FILE' in MDefs
:
3684 UNIFile
= os
.path
.join(self
.MetaFile
.Dir
, MDefs
['MODULE_UNI_FILE'])
3685 if os
.path
.isfile(UNIFile
):
3686 shutil
.copy2(UNIFile
, self
.OutputDir
)
3688 if self
.AutoGenVersion
> int(gInfSpecVersion
, 0):
3689 AsBuiltInfDict
['module_inf_version'] = '0x%08x' % self
.AutoGenVersion
3691 AsBuiltInfDict
['module_inf_version'] = gInfSpecVersion
3694 AsBuiltInfDict
['pcd_is_driver_string'].append(DriverType
)
3696 if 'UEFI_SPECIFICATION_VERSION' in self
.Specification
:
3697 AsBuiltInfDict
['module_uefi_specification_version'].append(self
.Specification
['UEFI_SPECIFICATION_VERSION'])
3698 if 'PI_SPECIFICATION_VERSION' in self
.Specification
:
3699 AsBuiltInfDict
['module_pi_specification_version'].append(self
.Specification
['PI_SPECIFICATION_VERSION'])
3701 OutputDir
= self
.OutputDir
.replace('\\', '/').strip('/')
3702 DebugDir
= self
.DebugDir
.replace('\\', '/').strip('/')
3703 for Item
in self
.CodaTargetList
:
3704 File
= Item
.Target
.Path
.replace('\\', '/').strip('/').replace(DebugDir
, '').replace(OutputDir
, '').strip('/')
3705 self
.OutputFile
.add(File
)
3706 if os
.path
.isabs(File
):
3707 File
= File
.replace('\\', '/').strip('/').replace(OutputDir
, '').strip('/')
3708 if Item
.Target
.Ext
.lower() == '.aml':
3709 AsBuiltInfDict
['binary_item'].append('ASL|' + File
)
3710 elif Item
.Target
.Ext
.lower() == '.acpi':
3711 AsBuiltInfDict
['binary_item'].append('ACPI|' + File
)
3712 elif Item
.Target
.Ext
.lower() == '.efi':
3713 AsBuiltInfDict
['binary_item'].append('PE32|' + self
.Name
+ '.efi')
3715 AsBuiltInfDict
['binary_item'].append('BIN|' + File
)
3716 if not self
.DepexGenerated
:
3717 DepexFile
= os
.path
.join(self
.OutputDir
, self
.Name
+ '.depex')
3718 if os
.path
.exists(DepexFile
):
3719 self
.DepexGenerated
= True
3720 if self
.DepexGenerated
:
3721 self
.OutputFile
.add(self
.Name
+ '.depex')
3722 if self
.ModuleType
in [SUP_MODULE_PEIM
]:
3723 AsBuiltInfDict
['binary_item'].append('PEI_DEPEX|' + self
.Name
+ '.depex')
3724 elif self
.ModuleType
in [SUP_MODULE_DXE_DRIVER
, SUP_MODULE_DXE_RUNTIME_DRIVER
, SUP_MODULE_DXE_SAL_DRIVER
, SUP_MODULE_UEFI_DRIVER
]:
3725 AsBuiltInfDict
['binary_item'].append('DXE_DEPEX|' + self
.Name
+ '.depex')
3726 elif self
.ModuleType
in [SUP_MODULE_DXE_SMM_DRIVER
]:
3727 AsBuiltInfDict
['binary_item'].append('SMM_DEPEX|' + self
.Name
+ '.depex')
3729 Bin
= self
._GenOffsetBin
()
3731 AsBuiltInfDict
['binary_item'].append('BIN|%s' % Bin
)
3732 self
.OutputFile
.add(Bin
)
3734 for Root
, Dirs
, Files
in os
.walk(OutputDir
):
3736 if File
.lower().endswith('.pdb'):
3737 AsBuiltInfDict
['binary_item'].append('DISPOSABLE|' + File
)
3738 self
.OutputFile
.add(File
)
3739 HeaderComments
= self
.Module
.HeaderComments
3741 for Index
in range(len(HeaderComments
)):
3742 if HeaderComments
[Index
].find('@BinaryHeader') != -1:
3743 HeaderComments
[Index
] = HeaderComments
[Index
].replace('@BinaryHeader', '@file')
3746 AsBuiltInfDict
['header_comments'] = '\n'.join(HeaderComments
[StartPos
:]).replace(':#', '://')
3747 AsBuiltInfDict
['tail_comments'] = '\n'.join(self
.Module
.TailComments
)
3750 (self
.ProtocolList
, self
._ProtocolComments
, 'protocol_item'),
3751 (self
.PpiList
, self
._PpiComments
, 'ppi_item'),
3752 (GuidList
, self
._GuidComments
, 'guid_item')
3754 for Item
in GenList
:
3755 for CName
in Item
[0]:
3756 Comments
= '\n '.join(Item
[1][CName
]) if CName
in Item
[1] else ''
3757 Entry
= Comments
+ '\n ' + CName
if Comments
else CName
3758 AsBuiltInfDict
[Item
[2]].append(Entry
)
3759 PatchList
= parsePcdInfoFromMapFile(
3760 os
.path
.join(self
.OutputDir
, self
.Name
+ '.map'),
3761 os
.path
.join(self
.OutputDir
, self
.Name
+ '.efi')
3764 for Pcd
in PatchablePcds
:
3765 TokenCName
= Pcd
.TokenCName
3766 for PcdItem
in GlobalData
.MixedPcd
:
3767 if (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
3768 TokenCName
= PcdItem
[0]
3770 for PatchPcd
in PatchList
:
3771 if TokenCName
== PatchPcd
[0]:
3776 if Pcd
.DatumType
== 'BOOLEAN':
3777 BoolValue
= Pcd
.DefaultValue
.upper()
3778 if BoolValue
== 'TRUE':
3779 Pcd
.DefaultValue
= '1'
3780 elif BoolValue
== 'FALSE':
3781 Pcd
.DefaultValue
= '0'
3783 if Pcd
.DatumType
in TAB_PCD_NUMERIC_TYPES
:
3784 HexFormat
= '0x%02x'
3785 if Pcd
.DatumType
== TAB_UINT16
:
3786 HexFormat
= '0x%04x'
3787 elif Pcd
.DatumType
== TAB_UINT32
:
3788 HexFormat
= '0x%08x'
3789 elif Pcd
.DatumType
== TAB_UINT64
:
3790 HexFormat
= '0x%016x'
3791 PcdValue
= HexFormat
% int(Pcd
.DefaultValue
, 0)
3793 if Pcd
.MaxDatumSize
is None or Pcd
.MaxDatumSize
== '':
3794 EdkLogger
.error("build", AUTOGEN_ERROR
,
3795 "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
3797 ArraySize
= int(Pcd
.MaxDatumSize
, 0)
3798 PcdValue
= Pcd
.DefaultValue
3799 if PcdValue
[0] != '{':
3801 if PcdValue
[0] == 'L':
3803 PcdValue
= PcdValue
.lstrip('L')
3804 PcdValue
= eval(PcdValue
)
3806 for Index
in range(0, len(PcdValue
)):
3808 CharVal
= ord(PcdValue
[Index
])
3809 NewValue
= NewValue
+ '0x%02x' % (CharVal
& 0x00FF) + ', ' \
3810 + '0x%02x' % (CharVal
>> 8) + ', '
3812 NewValue
= NewValue
+ '0x%02x' % (ord(PcdValue
[Index
]) % 0x100) + ', '
3815 Padding
= Padding
* 2
3816 ArraySize
= ArraySize
/ 2
3817 if ArraySize
< (len(PcdValue
) + 1):
3818 if Pcd
.MaxSizeUserSet
:
3819 EdkLogger
.error("build", AUTOGEN_ERROR
,
3820 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
3823 ArraySize
= len(PcdValue
) + 1
3824 if ArraySize
> len(PcdValue
) + 1:
3825 NewValue
= NewValue
+ Padding
* (ArraySize
- len(PcdValue
) - 1)
3826 PcdValue
= NewValue
+ Padding
.strip().rstrip(',') + '}'
3827 elif len(PcdValue
.split(',')) <= ArraySize
:
3828 PcdValue
= PcdValue
.rstrip('}') + ', 0x00' * (ArraySize
- len(PcdValue
.split(',')))
3831 if Pcd
.MaxSizeUserSet
:
3832 EdkLogger
.error("build", AUTOGEN_ERROR
,
3833 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
3836 ArraySize
= len(PcdValue
) + 1
3837 PcdItem
= '%s.%s|%s|0x%X' % \
3838 (Pcd
.TokenSpaceGuidCName
, TokenCName
, PcdValue
, PatchPcd
[1])
3840 if (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) in self
._PcdComments
:
3841 PcdComments
= '\n '.join(self
._PcdComments
[Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
])
3843 PcdItem
= PcdComments
+ '\n ' + PcdItem
3844 AsBuiltInfDict
['patchablepcd_item'].append(PcdItem
)
3846 for Pcd
in Pcds
+ VfrPcds
:
3849 TokenCName
= Pcd
.TokenCName
3850 for PcdItem
in GlobalData
.MixedPcd
:
3851 if (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
3852 TokenCName
= PcdItem
[0]
3854 if Pcd
.Type
== TAB_PCDS_DYNAMIC_EX_HII
:
3855 for SkuName
in Pcd
.SkuInfoList
:
3856 SkuInfo
= Pcd
.SkuInfoList
[SkuName
]
3857 HiiInfo
= '## %s|%s|%s' % (SkuInfo
.VariableName
, SkuInfo
.VariableGuid
, SkuInfo
.VariableOffset
)
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'].append(PcdEntry
)
3879 for Item
in self
.BuildOption
:
3880 if 'FLAGS' in self
.BuildOption
[Item
]:
3881 AsBuiltInfDict
['flags_item'].append('%s:%s_%s_%s_%s_FLAGS = %s' % (self
.ToolChainFamily
, self
.BuildTarget
, self
.ToolChain
, self
.Arch
, Item
, self
.BuildOption
[Item
]['FLAGS'].strip()))
3883 # Generated LibraryClasses section in comments.
3884 for Library
in self
.LibraryAutoGenList
:
3885 AsBuiltInfDict
['libraryclasses_item'].append(Library
.MetaFile
.File
.replace('\\', '/'))
3887 # Generated UserExtensions TianoCore section.
3888 # All tianocore user extensions are copied.
3890 for TianoCore
in self
._GetTianoCoreUserExtensionList
():
3891 UserExtStr
+= '\n'.join(TianoCore
)
3892 ExtensionFile
= os
.path
.join(self
.MetaFile
.Dir
, TianoCore
[1])
3893 if os
.path
.isfile(ExtensionFile
):
3894 shutil
.copy2(ExtensionFile
, self
.OutputDir
)
3895 AsBuiltInfDict
['userextension_tianocore_item'] = UserExtStr
3897 # Generated depex expression section in comments.
3898 DepexExpresion
= self
._GetDepexExpresionString
()
3899 AsBuiltInfDict
['depexsection_item'] = DepexExpresion
if DepexExpresion
else ''
3901 AsBuiltInf
= TemplateString()
3902 AsBuiltInf
.Append(gAsBuiltInfHeaderString
.Replace(AsBuiltInfDict
))
3904 SaveFileOnChange(os
.path
.join(self
.OutputDir
, self
.Name
+ '.inf'), str(AsBuiltInf
), False)
3906 self
.IsAsBuiltInfCreated
= True
3907 if GlobalData
.gBinCacheDest
:
3908 self
.CopyModuleToCache()
3910 def CopyModuleToCache(self
):
3911 FileDir
= path
.join(GlobalData
.gBinCacheDest
, self
.Arch
, self
.SourceDir
, self
.MetaFile
.BaseName
)
3912 CreateDirectory (FileDir
)
3913 HashFile
= path
.join(self
.BuildDir
, self
.Name
+ '.hash')
3914 ModuleFile
= path
.join(self
.OutputDir
, self
.Name
+ '.inf')
3915 if os
.path
.exists(HashFile
):
3916 shutil
.copy2(HashFile
, FileDir
)
3917 if os
.path
.exists(ModuleFile
):
3918 shutil
.copy2(ModuleFile
, FileDir
)
3919 if not self
.OutputFile
:
3920 Ma
= self
.BuildDatabase
[PathClass(ModuleFile
), self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
3921 self
.OutputFile
= Ma
.Binaries
3923 for File
in self
.OutputFile
:
3925 if not os
.path
.isabs(File
):
3926 File
= os
.path
.join(self
.OutputDir
, File
)
3927 if os
.path
.exists(File
):
3928 shutil
.copy2(File
, FileDir
)
3930 def AttemptModuleCacheCopy(self
):
3931 if self
.IsBinaryModule
:
3933 FileDir
= path
.join(GlobalData
.gBinCacheSource
, self
.Arch
, self
.SourceDir
, self
.MetaFile
.BaseName
)
3934 HashFile
= path
.join(FileDir
, self
.Name
+ '.hash')
3935 if os
.path
.exists(HashFile
):
3936 f
= open(HashFile
, 'r')
3937 CacheHash
= f
.read()
3939 if GlobalData
.gModuleHash
[self
.Arch
][self
.Name
]:
3940 if CacheHash
== GlobalData
.gModuleHash
[self
.Arch
][self
.Name
]:
3941 for root
, dir, files
in os
.walk(FileDir
):
3943 if self
.Name
+ '.hash' in f
:
3944 shutil
.copy2(HashFile
, self
.BuildDir
)
3946 File
= path
.join(root
, f
)
3947 shutil
.copy2(File
, self
.OutputDir
)
3948 if self
.Name
== "PcdPeim" or self
.Name
== "PcdDxe":
3949 CreatePcdDatabaseCode(self
, TemplateString(), TemplateString())
3953 ## Create makefile for the module and its dependent libraries
3955 # @param CreateLibraryMakeFile Flag indicating if or not the makefiles of
3956 # dependent libraries will be created
3958 @cached_class_function
3959 def CreateMakeFile(self
, CreateLibraryMakeFile
=True, GenFfsList
= []):
3960 # nest this function inside it's only caller.
3961 def CreateTimeStamp():
3962 FileSet
= {self
.MetaFile
.Path
}
3964 for SourceFile
in self
.Module
.Sources
:
3965 FileSet
.add (SourceFile
.Path
)
3967 for Lib
in self
.DependentLibraryList
:
3968 FileSet
.add (Lib
.MetaFile
.Path
)
3970 for f
in self
.AutoGenDepSet
:
3971 FileSet
.add (f
.Path
)
3973 if os
.path
.exists (self
.TimeStampPath
):
3974 os
.remove (self
.TimeStampPath
)
3975 with
open(self
.TimeStampPath
, 'w+') as file:
3979 # Ignore generating makefile when it is a binary module
3980 if self
.IsBinaryModule
:
3983 self
.GenFfsList
= GenFfsList
3984 if not self
.IsLibrary
and CreateLibraryMakeFile
:
3985 for LibraryAutoGen
in self
.LibraryAutoGenList
:
3986 LibraryAutoGen
.CreateMakeFile()
3991 if len(self
.CustomMakefile
) == 0:
3992 Makefile
= GenMake
.ModuleMakefile(self
)
3994 Makefile
= GenMake
.CustomMakefile(self
)
3995 if Makefile
.Generate():
3996 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated makefile for module %s [%s]" %
3997 (self
.Name
, self
.Arch
))
3999 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Skipped the generation of makefile for module %s [%s]" %
4000 (self
.Name
, self
.Arch
))
4004 def CopyBinaryFiles(self
):
4005 for File
in self
.Module
.Binaries
:
4007 DstPath
= os
.path
.join(self
.OutputDir
, os
.path
.basename(SrcPath
))
4008 CopyLongFilePath(SrcPath
, DstPath
)
4009 ## Create autogen code for the module and its dependent libraries
4011 # @param CreateLibraryCodeFile Flag indicating if or not the code of
4012 # dependent libraries will be created
4014 def CreateCodeFile(self
, CreateLibraryCodeFile
=True):
4015 if self
.IsCodeFileCreated
:
4018 # Need to generate PcdDatabase even PcdDriver is binarymodule
4019 if self
.IsBinaryModule
and self
.PcdIsDriver
!= '':
4020 CreatePcdDatabaseCode(self
, TemplateString(), TemplateString())
4022 if self
.IsBinaryModule
:
4024 self
.CopyBinaryFiles()
4027 if not self
.IsLibrary
and CreateLibraryCodeFile
:
4028 for LibraryAutoGen
in self
.LibraryAutoGenList
:
4029 LibraryAutoGen
.CreateCodeFile()
4035 IgoredAutoGenList
= []
4037 for File
in self
.AutoGenFileList
:
4038 if GenC
.Generate(File
.Path
, self
.AutoGenFileList
[File
], File
.IsBinary
):
4039 AutoGenList
.append(str(File
))
4041 IgoredAutoGenList
.append(str(File
))
4044 for ModuleType
in self
.DepexList
:
4045 # Ignore empty [depex] section or [depex] section for SUP_MODULE_USER_DEFINED module
4046 if len(self
.DepexList
[ModuleType
]) == 0 or ModuleType
== SUP_MODULE_USER_DEFINED
:
4049 Dpx
= GenDepex
.DependencyExpression(self
.DepexList
[ModuleType
], ModuleType
, True)
4050 DpxFile
= gAutoGenDepexFileName
% {"module_name" : self
.Name
}
4052 if len(Dpx
.PostfixNotation
) != 0:
4053 self
.DepexGenerated
= True
4055 if Dpx
.Generate(path
.join(self
.OutputDir
, DpxFile
)):
4056 AutoGenList
.append(str(DpxFile
))
4058 IgoredAutoGenList
.append(str(DpxFile
))
4060 if IgoredAutoGenList
== []:
4061 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated [%s] files for module %s [%s]" %
4062 (" ".join(AutoGenList
), self
.Name
, self
.Arch
))
4063 elif AutoGenList
== []:
4064 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Skipped the generation of [%s] files for module %s [%s]" %
4065 (" ".join(IgoredAutoGenList
), self
.Name
, self
.Arch
))
4067 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated [%s] (skipped %s) files for module %s [%s]" %
4068 (" ".join(AutoGenList
), " ".join(IgoredAutoGenList
), self
.Name
, self
.Arch
))
4070 self
.IsCodeFileCreated
= True
4073 ## Summarize the ModuleAutoGen objects of all libraries used by this module
4075 def LibraryAutoGenList(self
):
4077 for Library
in self
.DependentLibraryList
:
4084 self
.PlatformInfo
.MetaFile
4086 if La
not in RetVal
:
4088 for Lib
in La
.CodaTargetList
:
4089 self
._ApplyBuildRule
(Lib
.Target
, TAB_UNKNOWN_FILE
)
4092 def GenModuleHash(self
):
4093 if self
.Arch
not in GlobalData
.gModuleHash
:
4094 GlobalData
.gModuleHash
[self
.Arch
] = {}
4096 # Add Platform level hash
4097 m
.update(GlobalData
.gPlatformHash
)
4098 # Add Package level hash
4099 if self
.DependentPackageList
:
4100 for Pkg
in sorted(self
.DependentPackageList
, key
=lambda x
: x
.PackageName
):
4101 if Pkg
.PackageName
in GlobalData
.gPackageHash
[self
.Arch
]:
4102 m
.update(GlobalData
.gPackageHash
[self
.Arch
][Pkg
.PackageName
])
4105 if self
.LibraryAutoGenList
:
4106 for Lib
in sorted(self
.LibraryAutoGenList
, key
=lambda x
: x
.Name
):
4107 if Lib
.Name
not in GlobalData
.gModuleHash
[self
.Arch
]:
4109 m
.update(GlobalData
.gModuleHash
[self
.Arch
][Lib
.Name
])
4112 f
= open(str(self
.MetaFile
), 'r')
4116 # Add Module's source files
4117 if self
.SourceFileList
:
4118 for File
in sorted(self
.SourceFileList
, key
=lambda x
: str(x
)):
4119 f
= open(str(File
), 'r')
4124 ModuleHashFile
= path
.join(self
.BuildDir
, self
.Name
+ ".hash")
4125 if self
.Name
not in GlobalData
.gModuleHash
[self
.Arch
]:
4126 GlobalData
.gModuleHash
[self
.Arch
][self
.Name
] = m
.hexdigest()
4127 if GlobalData
.gBinCacheSource
:
4128 if self
.AttemptModuleCacheCopy():
4130 return SaveFileOnChange(ModuleHashFile
, m
.hexdigest(), True)
4132 ## Decide whether we can skip the ModuleAutoGen process
4133 def CanSkipbyHash(self
):
4134 if GlobalData
.gUseHashCache
:
4135 return not self
.GenModuleHash()
4138 ## Decide whether we can skip the ModuleAutoGen process
4139 # If any source file is newer than the module than we cannot skip
4142 if self
.MakeFileDir
in GlobalData
.gSikpAutoGenCache
:
4144 if not os
.path
.exists(self
.TimeStampPath
):
4146 #last creation time of the module
4147 DstTimeStamp
= os
.stat(self
.TimeStampPath
)[8]
4149 SrcTimeStamp
= self
.Workspace
._SrcTimeStamp
4150 if SrcTimeStamp
> DstTimeStamp
:
4153 with
open(self
.TimeStampPath
,'r') as f
:
4155 source
= source
.rstrip('\n')
4156 if not os
.path
.exists(source
):
4158 if source
not in ModuleAutoGen
.TimeDict
:
4159 ModuleAutoGen
.TimeDict
[source
] = os
.stat(source
)[8]
4160 if ModuleAutoGen
.TimeDict
[source
] > DstTimeStamp
:
4162 GlobalData
.gSikpAutoGenCache
.add(self
.MakeFileDir
)
4166 def TimeStampPath(self
):
4167 return os
.path
.join(self
.MakeFileDir
, 'AutoGenTimeStamp')