]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/AutoGen/AutoGen.py
BaseTools: Handle the bytes and str difference
[mirror_edk2.git] / BaseTools / Source / Python / AutoGen / AutoGen.py
CommitLineData
52302d4d
LG
1## @file\r
2# Generate AutoGen.h, AutoGen.c and *.depex files\r
3#\r
e74cea4c 4# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>\r
3f34e36d
LD
5# Copyright (c) 2018, Hewlett Packard Enterprise Development, L.P.<BR>\r
6#\r
40d841f6 7# This program and the accompanying materials\r
52302d4d
LG
8# are licensed and made available under the terms and conditions of the BSD License\r
9# which accompanies this distribution. The full text of the license may be found at\r
10# http://opensource.org/licenses/bsd-license.php\r
11#\r
12# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
13# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
14#\r
15\r
16## Import Modules\r
17#\r
1be2ed90 18import Common.LongFilePathOs as os\r
52302d4d
LG
19import re\r
20import os.path as path\r
21import copy\r
867d1cd4 22import uuid\r
52302d4d 23\r
0ff3b52e
GL
24from . import GenC\r
25from . import GenMake\r
26from . import GenDepex\r
86379ac4 27from io import BytesIO\r
52302d4d 28\r
0ff3b52e
GL
29from .StrGather import *\r
30from .BuildEngine import BuildRule\r
52302d4d 31\r
1be2ed90 32from Common.LongFilePathSupport import CopyLongFilePath\r
52302d4d
LG
33from Common.BuildToolError import *\r
34from Common.DataType import *\r
35from Common.Misc import *\r
5a57246e 36from Common.StringUtils import *\r
52302d4d
LG
37import Common.GlobalData as GlobalData\r
38from GenFds.FdfParser import *\r
39from CommonDataClass.CommonClass import SkuInfoClass\r
e8a47801 40from GenPatchPcdTable.GenPatchPcdTable import parsePcdInfoFromMapFile\r
e56468c0 41import Common.VpdInfoFile as VpdInfoFile\r
0ff3b52e 42from .GenPcdDb import CreatePcdDatabaseCode\r
e8a47801 43from Workspace.MetaFileCommentParser import UsageList\r
c14b5861 44from Workspace.WorkspaceCommon import GetModuleLibInstances\r
05cc51ad 45from Common.MultipleWorkspace import MultipleWorkspace as mws\r
0ff3b52e 46from . import InfSectionParser\r
c17956e0 47import datetime\r
36d083ef 48import hashlib\r
0ff3b52e 49from .GenVar import VariableMgr, var_info\r
9006a2c6 50from collections import OrderedDict\r
a993dc03 51from collections import defaultdict\r
caf74495 52from Workspace.WorkspaceCommon import OrderedListDict\r
97fa0ee9 53\r
830bf22f 54from Common.caching import cached_property, cached_class_function\r
b23414f6 55\r
e8a47801 56## Regular expression for splitting Dependency Expression string into tokens\r
52302d4d
LG
57gDepexTokenPattern = re.compile("(\(|\)|\w+| \S+\.inf)")\r
58\r
c8802c3d
CJ
59## Regular expression for match: PCD(xxxx.yyy)\r
60gPCDAsGuidPattern = re.compile(r"^PCD\(.+\..+\)$")\r
61\r
62#\r
63# Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT\r
64# is the former use /I , the Latter used -I to specify include directories\r
65#\r
66gBuildOptIncludePatternMsft = re.compile(r"(?:.*?)/I[ \t]*([^ ]*)", re.MULTILINE | re.DOTALL)\r
67gBuildOptIncludePatternOther = re.compile(r"(?:.*?)-I[ \t]*([^ ]*)", re.MULTILINE | re.DOTALL)\r
68\r
97fa0ee9
YL
69#\r
70# Match name = variable\r
71#\r
72gEfiVarStoreNamePattern = re.compile("\s*name\s*=\s*(\w+)")\r
73#\r
74# The format of guid in efivarstore statement likes following and must be correct:\r
75# guid = {0xA04A27f4, 0xDF00, 0x4D42, {0xB5, 0x52, 0x39, 0x51, 0x13, 0x02, 0x11, 0x3D}}\r
76#\r
77gEfiVarStoreGuidPattern = re.compile("\s*guid\s*=\s*({.*?{.*?}\s*})")\r
78\r
52302d4d 79## Mapping Makefile type\r
94c04559 80gMakeTypeMap = {TAB_COMPILER_MSFT:"nmake", "GCC":"gmake"}\r
52302d4d
LG
81\r
82\r
83## Build rule configuration file\r
51de5c30 84gDefaultBuildRuleFile = 'build_rule.txt'\r
52302d4d 85\r
86601b78 86## Tools definition configuration file\r
51de5c30 87gDefaultToolsDefFile = 'tools_def.txt'\r
86601b78 88\r
64b2609f
LG
89## Build rule default version\r
90AutoGenReqBuildRuleVerNum = "0.1"\r
91\r
52302d4d
LG
92## default file name for AutoGen\r
93gAutoGenCodeFileName = "AutoGen.c"\r
94gAutoGenHeaderFileName = "AutoGen.h"\r
95gAutoGenStringFileName = "%(module_name)sStrDefs.h"\r
96gAutoGenStringFormFileName = "%(module_name)sStrDefs.hpk"\r
97gAutoGenDepexFileName = "%(module_name)s.depex"\r
333ba578
YZ
98gAutoGenImageDefFileName = "%(module_name)sImgDefs.h"\r
99gAutoGenIdfFileName = "%(module_name)sIdf.hpk"\r
97fa0ee9
YL
100gInfSpecVersion = "0x00010017"\r
101\r
da92f276
LG
102#\r
103# Template string to generic AsBuilt INF\r
104#\r
e8a47801 105gAsBuiltInfHeaderString = TemplateString("""${header_comments}\r
da92f276 106\r
97fa0ee9
YL
107# DO NOT EDIT\r
108# FILE auto-generated\r
109\r
da92f276 110[Defines]\r
97fa0ee9 111 INF_VERSION = ${module_inf_version}\r
da92f276
LG
112 BASE_NAME = ${module_name}\r
113 FILE_GUID = ${module_guid}\r
97fa0ee9
YL
114 MODULE_TYPE = ${module_module_type}${BEGIN}\r
115 VERSION_STRING = ${module_version_string}${END}${BEGIN}\r
e8a47801 116 PCD_IS_DRIVER = ${pcd_is_driver_string}${END}${BEGIN}\r
da92f276 117 UEFI_SPECIFICATION_VERSION = ${module_uefi_specification_version}${END}${BEGIN}\r
97fa0ee9
YL
118 PI_SPECIFICATION_VERSION = ${module_pi_specification_version}${END}${BEGIN}\r
119 ENTRY_POINT = ${module_entry_point}${END}${BEGIN}\r
120 UNLOAD_IMAGE = ${module_unload_image}${END}${BEGIN}\r
121 CONSTRUCTOR = ${module_constructor}${END}${BEGIN}\r
122 DESTRUCTOR = ${module_destructor}${END}${BEGIN}\r
123 SHADOW = ${module_shadow}${END}${BEGIN}\r
124 PCI_VENDOR_ID = ${module_pci_vendor_id}${END}${BEGIN}\r
125 PCI_DEVICE_ID = ${module_pci_device_id}${END}${BEGIN}\r
126 PCI_CLASS_CODE = ${module_pci_class_code}${END}${BEGIN}\r
127 PCI_REVISION = ${module_pci_revision}${END}${BEGIN}\r
128 BUILD_NUMBER = ${module_build_number}${END}${BEGIN}\r
129 SPEC = ${module_spec}${END}${BEGIN}\r
130 UEFI_HII_RESOURCE_SECTION = ${module_uefi_hii_resource_section}${END}${BEGIN}\r
131 MODULE_UNI_FILE = ${module_uni_file}${END}\r
132\r
133[Packages.${module_arch}]${BEGIN}\r
da92f276
LG
134 ${package_item}${END}\r
135\r
136[Binaries.${module_arch}]${BEGIN}\r
137 ${binary_item}${END}\r
138\r
e8a47801
LG
139[PatchPcd.${module_arch}]${BEGIN}\r
140 ${patchablepcd_item}\r
141${END}\r
97fa0ee9 142\r
e8a47801
LG
143[Protocols.${module_arch}]${BEGIN}\r
144 ${protocol_item}\r
145${END}\r
97fa0ee9 146\r
e8a47801
LG
147[Ppis.${module_arch}]${BEGIN}\r
148 ${ppi_item}\r
149${END}\r
97fa0ee9 150\r
e8a47801
LG
151[Guids.${module_arch}]${BEGIN}\r
152 ${guid_item}\r
153${END}\r
97fa0ee9 154\r
e8a47801
LG
155[PcdEx.${module_arch}]${BEGIN}\r
156 ${pcd_item}\r
157${END}\r
da92f276 158\r
97fa0ee9
YL
159[LibraryClasses.${module_arch}]\r
160## @LIB_INSTANCES${BEGIN}\r
161# ${libraryclasses_item}${END}\r
162\r
163${depexsection_item}\r
164\r
dfa41b4a
YZ
165${userextension_tianocore_item}\r
166\r
97fa0ee9
YL
167${tail_comments}\r
168\r
169[BuildOptions.${module_arch}]\r
da92f276
LG
170## @AsBuilt${BEGIN}\r
171## ${flags_item}${END}\r
172""")\r
173\r
52302d4d
LG
174## Base class for AutoGen\r
175#\r
176# This class just implements the cache mechanism of AutoGen objects.\r
177#\r
178class AutoGen(object):\r
b24e99f7
CJ
179 # database to maintain the objects in each child class\r
180 __ObjectCache = {} # (BuildTarget, ToolChain, ARCH, platform file): AutoGen object\r
52302d4d
LG
181\r
182 ## Factory method\r
183 #\r
184 # @param Class class object of real AutoGen class\r
185 # (WorkspaceAutoGen, ModuleAutoGen or PlatformAutoGen)\r
186 # @param Workspace Workspace directory or WorkspaceAutoGen object\r
187 # @param MetaFile The path of meta file\r
188 # @param Target Build target\r
189 # @param Toolchain Tool chain name\r
190 # @param Arch Target arch\r
191 # @param *args The specific class related parameters\r
192 # @param **kwargs The specific class related dict parameters\r
193 #\r
b24e99f7 194 def __new__(cls, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):\r
52302d4d 195 # check if the object has been created\r
b24e99f7 196 Key = (Target, Toolchain, Arch, MetaFile)\r
b23414f6 197 if Key in cls.__ObjectCache:\r
b24e99f7
CJ
198 # if it exists, just return it directly\r
199 return cls.__ObjectCache[Key]\r
b24e99f7 200 # it didnt exist. create it, cache it, then return it\r
4ce4f757 201 RetVal = cls.__ObjectCache[Key] = super().__new__(cls)\r
b23414f6 202 return RetVal\r
b24e99f7
CJ
203\r
204 def __init__ (self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):\r
4ce4f757 205 super().__init__()\r
52302d4d
LG
206\r
207 ## hash() operator\r
208 #\r
209 # The file path of platform file will be used to represent hash value of this object\r
210 #\r
211 # @retval int Hash value of the file path of platform file\r
212 #\r
213 def __hash__(self):\r
214 return hash(self.MetaFile)\r
215\r
216 ## str() operator\r
217 #\r
218 # The file path of platform file will be used to represent this object\r
219 #\r
220 # @retval string String of platform file path\r
221 #\r
222 def __str__(self):\r
223 return str(self.MetaFile)\r
224\r
225 ## "==" operator\r
226 def __eq__(self, Other):\r
227 return Other and self.MetaFile == Other\r
228\r
229## Workspace AutoGen class\r
230#\r
231# This class is used mainly to control the whole platform build for different\r
232# architecture. This class will generate top level makefile.\r
233#\r
234class WorkspaceAutoGen(AutoGen):\r
b24e99f7
CJ
235 # call super().__init__ then call the worker function with different parameter count\r
236 def __init__(self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):\r
b23414f6 237 if not hasattr(self, "_Init"):\r
4ce4f757 238 super().__init__(Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)\r
b24e99f7
CJ
239 self._InitWorker(Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)\r
240 self._Init = True\r
f7496d71 241\r
b24e99f7 242 ## Initialize WorkspaceAutoGen\r
52302d4d
LG
243 #\r
244 # @param WorkspaceDir Root directory of workspace\r
245 # @param ActivePlatform Meta-file of active platform\r
246 # @param Target Build target\r
247 # @param Toolchain Tool chain name\r
248 # @param ArchList List of architecture of current build\r
249 # @param MetaFileDb Database containing meta-files\r
250 # @param BuildConfig Configuration of build\r
251 # @param ToolDefinition Tool chain definitions\r
252 # @param FlashDefinitionFile File of flash definition\r
253 # @param Fds FD list to be generated\r
254 # @param Fvs FV list to be generated\r
4234283c 255 # @param Caps Capsule list to be generated\r
52302d4d
LG
256 # @param SkuId SKU id from command line\r
257 #\r
b24e99f7 258 def _InitWorker(self, WorkspaceDir, ActivePlatform, Target, Toolchain, ArchList, MetaFileDb,\r
47fea6af 259 BuildConfig, ToolDefinition, FlashDefinitionFile='', Fds=None, Fvs=None, Caps=None, SkuId='', UniFlag=None,\r
9508d0fa 260 Progress=None, BuildModule=None):\r
0d2711a6
LG
261 self.BuildDatabase = MetaFileDb\r
262 self.MetaFile = ActivePlatform\r
52302d4d 263 self.WorkspaceDir = WorkspaceDir\r
6b1f2cf4 264 self.Platform = self.BuildDatabase[self.MetaFile, TAB_ARCH_COMMON, Target, Toolchain]\r
d0acc87a 265 GlobalData.gActivePlatform = self.Platform\r
52302d4d
LG
266 self.BuildTarget = Target\r
267 self.ToolChain = Toolchain\r
268 self.ArchList = ArchList\r
269 self.SkuId = SkuId\r
f3decdc3 270 self.UniFlag = UniFlag\r
52302d4d 271\r
52302d4d
LG
272 self.TargetTxt = BuildConfig\r
273 self.ToolDef = ToolDefinition\r
274 self.FdfFile = FlashDefinitionFile\r
066c7154
CJ
275 self.FdTargetList = Fds if Fds else []\r
276 self.FvTargetList = Fvs if Fvs else []\r
277 self.CapTargetList = Caps if Caps else []\r
52302d4d 278 self.AutoGenObjectList = []\r
726c501c 279 self._GuidDict = {}\r
52302d4d
LG
280\r
281 # there's many relative directory operations, so ...\r
282 os.chdir(self.WorkspaceDir)\r
283\r
0d2711a6
LG
284 #\r
285 # Merge Arch\r
286 #\r
287 if not self.ArchList:\r
288 ArchList = set(self.Platform.SupArchList)\r
289 else:\r
290 ArchList = set(self.ArchList) & set(self.Platform.SupArchList)\r
291 if not ArchList:\r
292 EdkLogger.error("build", PARAMETER_INVALID,\r
293 ExtraData = "Invalid ARCH specified. [Valid ARCH: %s]" % (" ".join(self.Platform.SupArchList)))\r
294 elif self.ArchList and len(ArchList) != len(self.ArchList):\r
295 SkippedArchList = set(self.ArchList).symmetric_difference(set(self.Platform.SupArchList))\r
296 EdkLogger.verbose("\nArch [%s] is ignored because the platform supports [%s] only!"\r
297 % (" ".join(SkippedArchList), " ".join(self.Platform.SupArchList)))\r
298 self.ArchList = tuple(ArchList)\r
299\r
300 # Validate build target\r
301 if self.BuildTarget not in self.Platform.BuildTargets:\r
47fea6af 302 EdkLogger.error("build", PARAMETER_INVALID,\r
0d2711a6
LG
303 ExtraData="Build target [%s] is not supported by the platform. [Valid target: %s]"\r
304 % (self.BuildTarget, " ".join(self.Platform.BuildTargets)))\r
305\r
f7496d71 306\r
52302d4d 307 # parse FDF file to get PCDs in it, if any\r
0d2711a6
LG
308 if not self.FdfFile:\r
309 self.FdfFile = self.Platform.FlashDefinition\r
47fea6af 310\r
9508d0fa
LG
311 EdkLogger.info("")\r
312 if self.ArchList:\r
313 EdkLogger.info('%-16s = %s' % ("Architecture(s)", ' '.join(self.ArchList)))\r
314 EdkLogger.info('%-16s = %s' % ("Build target", self.BuildTarget))\r
47fea6af
YZ
315 EdkLogger.info('%-16s = %s' % ("Toolchain", self.ToolChain))\r
316\r
9508d0fa
LG
317 EdkLogger.info('\n%-24s = %s' % ("Active Platform", self.Platform))\r
318 if BuildModule:\r
319 EdkLogger.info('%-24s = %s' % ("Active Module", BuildModule))\r
47fea6af 320\r
9508d0fa
LG
321 if self.FdfFile:\r
322 EdkLogger.info('%-24s = %s' % ("Flash Image Definition", self.FdfFile))\r
0d2711a6 323\r
9508d0fa 324 EdkLogger.verbose("\nFLASH_DEFINITION = %s" % self.FdfFile)\r
47fea6af 325\r
e74cea4c
YZ
326 if Progress:\r
327 Progress.Start("\nProcessing meta-data")\r
47fea6af 328\r
0d2711a6 329 if self.FdfFile:\r
df692f02
LG
330 #\r
331 # Mark now build in AutoGen Phase\r
332 #\r
47fea6af 333 GlobalData.gAutoGenPhase = True\r
52302d4d
LG
334 Fdf = FdfParser(self.FdfFile.Path)\r
335 Fdf.ParseFile()\r
a0a2cd1e 336 GlobalData.gFdfParser = Fdf\r
0d2711a6 337 GlobalData.gAutoGenPhase = False\r
52302d4d 338 PcdSet = Fdf.Profile.PcdDict\r
cb04330e
YZ
339 if Fdf.CurrentFdName and Fdf.CurrentFdName in Fdf.Profile.FdDict:\r
340 FdDict = Fdf.Profile.FdDict[Fdf.CurrentFdName]\r
341 for FdRegion in FdDict.RegionList:\r
342 if str(FdRegion.RegionType) is 'FILE' and self.Platform.VpdToolGuid in str(FdRegion.RegionDataList):\r
343 if int(FdRegion.Offset) % 8 != 0:\r
344 EdkLogger.error("build", FORMAT_INVALID, 'The VPD Base Address %s must be 8-byte aligned.' % (FdRegion.Offset))\r
52302d4d
LG
345 ModuleList = Fdf.Profile.InfList\r
346 self.FdfProfile = Fdf.Profile\r
0d2711a6
LG
347 for fvname in self.FvTargetList:\r
348 if fvname.upper() not in self.FdfProfile.FvDict:\r
349 EdkLogger.error("build", OPTION_VALUE_INVALID,\r
350 "No such an FV in FDF file: %s" % fvname)\r
2502b735 351\r
622b1758
YZ
352 # In DSC file may use FILE_GUID to override the module, then in the Platform.Modules use FILE_GUIDmodule.inf as key,\r
353 # but the path (self.MetaFile.Path) is the real path\r
2502b735
YZ
354 for key in self.FdfProfile.InfDict:\r
355 if key == 'ArchTBD':\r
992fbe35 356 MetaFile_cache = defaultdict(set)\r
2502b735 357 for Arch in self.ArchList:\r
1530ceda 358 Current_Platform_cache = self.BuildDatabase[self.MetaFile, Arch, Target, Toolchain]\r
1530ceda
CJ
359 for Pkey in Current_Platform_cache.Modules:\r
360 MetaFile_cache[Arch].add(Current_Platform_cache.Modules[Pkey].MetaFile)\r
2502b735
YZ
361 for Inf in self.FdfProfile.InfDict[key]:\r
362 ModuleFile = PathClass(NormPath(Inf), GlobalData.gWorkspace, Arch)\r
363 for Arch in self.ArchList:\r
622b1758 364 if ModuleFile in MetaFile_cache[Arch]:\r
2502b735
YZ
365 break\r
366 else:\r
367 ModuleData = self.BuildDatabase[ModuleFile, Arch, Target, Toolchain]\r
368 if not ModuleData.IsBinaryModule:\r
369 EdkLogger.error('build', PARSER_ERROR, "Module %s NOT found in DSC file; Is it really a binary module?" % ModuleFile)\r
370\r
371 else:\r
372 for Arch in self.ArchList:\r
373 if Arch == key:\r
374 Platform = self.BuildDatabase[self.MetaFile, Arch, Target, Toolchain]\r
b74b419a
CJ
375 MetaFileList = set()\r
376 for Pkey in Platform.Modules:\r
377 MetaFileList.add(Platform.Modules[Pkey].MetaFile)\r
2502b735
YZ
378 for Inf in self.FdfProfile.InfDict[key]:\r
379 ModuleFile = PathClass(NormPath(Inf), GlobalData.gWorkspace, Arch)\r
622b1758 380 if ModuleFile in MetaFileList:\r
2502b735
YZ
381 continue\r
382 ModuleData = self.BuildDatabase[ModuleFile, Arch, Target, Toolchain]\r
383 if not ModuleData.IsBinaryModule:\r
384 EdkLogger.error('build', PARSER_ERROR, "Module %s NOT found in DSC file; Is it really a binary module?" % ModuleFile)\r
385\r
52302d4d
LG
386 else:\r
387 PcdSet = {}\r
388 ModuleList = []\r
389 self.FdfProfile = None\r
0d2711a6
LG
390 if self.FdTargetList:\r
391 EdkLogger.info("No flash definition file found. FD [%s] will be ignored." % " ".join(self.FdTargetList))\r
392 self.FdTargetList = []\r
393 if self.FvTargetList:\r
394 EdkLogger.info("No flash definition file found. FV [%s] will be ignored." % " ".join(self.FvTargetList))\r
395 self.FvTargetList = []\r
396 if self.CapTargetList:\r
397 EdkLogger.info("No flash definition file found. Capsule [%s] will be ignored." % " ".join(self.CapTargetList))\r
398 self.CapTargetList = []\r
47fea6af 399\r
52302d4d
LG
400 # apply SKU and inject PCDs from Flash Definition file\r
401 for Arch in self.ArchList:\r
0d2711a6 402 Platform = self.BuildDatabase[self.MetaFile, Arch, Target, Toolchain]\r
f9fa014e
YZ
403 PlatformPcds = Platform.Pcds\r
404 self._GuidDict = Platform._GuidDict\r
6b1f2cf4
CJ
405 SourcePcdDict = {TAB_PCDS_DYNAMIC_EX:set(), TAB_PCDS_PATCHABLE_IN_MODULE:set(),TAB_PCDS_DYNAMIC:set(),TAB_PCDS_FIXED_AT_BUILD:set()}\r
406 BinaryPcdDict = {TAB_PCDS_DYNAMIC_EX:set(), TAB_PCDS_PATCHABLE_IN_MODULE:set()}\r
2a29017e
YZ
407 SourcePcdDict_Keys = SourcePcdDict.keys()\r
408 BinaryPcdDict_Keys = BinaryPcdDict.keys()\r
409\r
410 # generate the SourcePcdDict and BinaryPcdDict\r
6f49996c 411 PGen = PlatformAutoGen(self, self.MetaFile, Target, Toolchain, Arch)\r
2a29017e
YZ
412 for BuildData in PGen.BuildDatabase._CACHE_.values():\r
413 if BuildData.Arch != Arch:\r
414 continue\r
415 if BuildData.MetaFile.Ext == '.inf':\r
416 for key in BuildData.Pcds:\r
417 if BuildData.Pcds[key].Pending:\r
418 if key in Platform.Pcds:\r
419 PcdInPlatform = Platform.Pcds[key]\r
c93356ad 420 if PcdInPlatform.Type:\r
2a29017e 421 BuildData.Pcds[key].Type = PcdInPlatform.Type\r
74f59e92 422 BuildData.Pcds[key].Pending = False\r
2a29017e
YZ
423\r
424 if BuildData.MetaFile in Platform.Modules:\r
425 PlatformModule = Platform.Modules[str(BuildData.MetaFile)]\r
426 if key in PlatformModule.Pcds:\r
427 PcdInPlatform = PlatformModule.Pcds[key]\r
c93356ad 428 if PcdInPlatform.Type:\r
2a29017e 429 BuildData.Pcds[key].Type = PcdInPlatform.Type\r
74f59e92 430 BuildData.Pcds[key].Pending = False\r
5a444dfd
YF
431 else:\r
432 #Pcd used in Library, Pcd Type from reference module if Pcd Type is Pending\r
433 if BuildData.Pcds[key].Pending:\r
434 MGen = ModuleAutoGen(self, BuildData.MetaFile, Target, Toolchain, Arch, self.MetaFile)\r
435 if MGen and MGen.IsLibrary:\r
436 if MGen in PGen.LibraryAutoGenList:\r
b23414f6 437 ReferenceModules = MGen.ReferenceModules\r
5a444dfd
YF
438 for ReferenceModule in ReferenceModules:\r
439 if ReferenceModule.MetaFile in Platform.Modules:\r
440 RefPlatformModule = Platform.Modules[str(ReferenceModule.MetaFile)]\r
441 if key in RefPlatformModule.Pcds:\r
442 PcdInReferenceModule = RefPlatformModule.Pcds[key]\r
443 if PcdInReferenceModule.Type:\r
444 BuildData.Pcds[key].Type = PcdInReferenceModule.Type\r
445 BuildData.Pcds[key].Pending = False\r
446 break\r
2a29017e 447\r
6b1f2cf4 448 if TAB_PCDS_DYNAMIC_EX in BuildData.Pcds[key].Type:\r
2a29017e 449 if BuildData.IsBinaryModule:\r
6b1f2cf4 450 BinaryPcdDict[TAB_PCDS_DYNAMIC_EX].add((BuildData.Pcds[key].TokenCName, BuildData.Pcds[key].TokenSpaceGuidCName))\r
2a29017e 451 else:\r
6b1f2cf4 452 SourcePcdDict[TAB_PCDS_DYNAMIC_EX].add((BuildData.Pcds[key].TokenCName, BuildData.Pcds[key].TokenSpaceGuidCName))\r
2a29017e 453\r
6b1f2cf4 454 elif TAB_PCDS_PATCHABLE_IN_MODULE in BuildData.Pcds[key].Type:\r
2a29017e
YZ
455 if BuildData.MetaFile.Ext == '.inf':\r
456 if BuildData.IsBinaryModule:\r
6b1f2cf4 457 BinaryPcdDict[TAB_PCDS_PATCHABLE_IN_MODULE].add((BuildData.Pcds[key].TokenCName, BuildData.Pcds[key].TokenSpaceGuidCName))\r
2a29017e 458 else:\r
6b1f2cf4 459 SourcePcdDict[TAB_PCDS_PATCHABLE_IN_MODULE].add((BuildData.Pcds[key].TokenCName, BuildData.Pcds[key].TokenSpaceGuidCName))\r
2a29017e 460\r
6b1f2cf4
CJ
461 elif TAB_PCDS_DYNAMIC in BuildData.Pcds[key].Type:\r
462 SourcePcdDict[TAB_PCDS_DYNAMIC].add((BuildData.Pcds[key].TokenCName, BuildData.Pcds[key].TokenSpaceGuidCName))\r
463 elif TAB_PCDS_FIXED_AT_BUILD in BuildData.Pcds[key].Type:\r
464 SourcePcdDict[TAB_PCDS_FIXED_AT_BUILD].add((BuildData.Pcds[key].TokenCName, BuildData.Pcds[key].TokenSpaceGuidCName))\r
2a29017e
YZ
465 else:\r
466 pass\r
97cdb33b
YZ
467 #\r
468 # A PCD can only use one type for all source modules\r
469 #\r
470 for i in SourcePcdDict_Keys:\r
471 for j in SourcePcdDict_Keys:\r
472 if i != j:\r
ff5635e9
CJ
473 Intersections = SourcePcdDict[i].intersection(SourcePcdDict[j])\r
474 if len(Intersections) > 0:\r
97cdb33b
YZ
475 EdkLogger.error(\r
476 'build',\r
477 FORMAT_INVALID,\r
478 "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),\r
caf74495 479 ExtraData='\n\t'.join(str(P[1]+'.'+P[0]) for P in Intersections)\r
97cdb33b 480 )\r
2a29017e
YZ
481\r
482 #\r
483 # intersection the BinaryPCD for Mixed PCD\r
484 #\r
485 for i in BinaryPcdDict_Keys:\r
486 for j in BinaryPcdDict_Keys:\r
487 if i != j:\r
ff5635e9
CJ
488 Intersections = BinaryPcdDict[i].intersection(BinaryPcdDict[j])\r
489 for item in Intersections:\r
2a29017e
YZ
490 NewPcd1 = (item[0] + '_' + i, item[1])\r
491 NewPcd2 = (item[0] + '_' + j, item[1])\r
492 if item not in GlobalData.MixedPcd:\r
493 GlobalData.MixedPcd[item] = [NewPcd1, NewPcd2]\r
494 else:\r
495 if NewPcd1 not in GlobalData.MixedPcd[item]:\r
496 GlobalData.MixedPcd[item].append(NewPcd1)\r
497 if NewPcd2 not in GlobalData.MixedPcd[item]:\r
498 GlobalData.MixedPcd[item].append(NewPcd2)\r
2a29017e
YZ
499\r
500 #\r
501 # intersection the SourcePCD and BinaryPCD for Mixed PCD\r
502 #\r
503 for i in SourcePcdDict_Keys:\r
504 for j in BinaryPcdDict_Keys:\r
505 if i != j:\r
ff5635e9
CJ
506 Intersections = SourcePcdDict[i].intersection(BinaryPcdDict[j])\r
507 for item in Intersections:\r
2a29017e
YZ
508 NewPcd1 = (item[0] + '_' + i, item[1])\r
509 NewPcd2 = (item[0] + '_' + j, item[1])\r
510 if item not in GlobalData.MixedPcd:\r
511 GlobalData.MixedPcd[item] = [NewPcd1, NewPcd2]\r
512 else:\r
513 if NewPcd1 not in GlobalData.MixedPcd[item]:\r
514 GlobalData.MixedPcd[item].append(NewPcd1)\r
515 if NewPcd2 not in GlobalData.MixedPcd[item]:\r
516 GlobalData.MixedPcd[item].append(NewPcd2)\r
2a29017e
YZ
517\r
518 for BuildData in PGen.BuildDatabase._CACHE_.values():\r
519 if BuildData.Arch != Arch:\r
520 continue\r
521 for key in BuildData.Pcds:\r
522 for SinglePcd in GlobalData.MixedPcd:\r
523 if (BuildData.Pcds[key].TokenCName, BuildData.Pcds[key].TokenSpaceGuidCName) == SinglePcd:\r
524 for item in GlobalData.MixedPcd[SinglePcd]:\r
525 Pcd_Type = item[0].split('_')[-1]\r
eece4292
CJ
526 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 \\r
527 (Pcd_Type == TAB_PCDS_DYNAMIC and BuildData.Pcds[key].Type in PCD_DYNAMIC_TYPE_SET):\r
2a29017e
YZ
528 Value = BuildData.Pcds[key]\r
529 Value.TokenCName = BuildData.Pcds[key].TokenCName + '_' + Pcd_Type\r
530 if len(key) == 2:\r
531 newkey = (Value.TokenCName, key[1])\r
532 elif len(key) == 3:\r
533 newkey = (Value.TokenCName, key[1], key[2])\r
534 del BuildData.Pcds[key]\r
535 BuildData.Pcds[newkey] = Value\r
536 break\r
2a29017e 537 break\r
2a29017e
YZ
538\r
539 # handle the mixed pcd in FDF file\r
540 for key in PcdSet:\r
541 if key in GlobalData.MixedPcd:\r
542 Value = PcdSet[key]\r
543 del PcdSet[key]\r
544 for item in GlobalData.MixedPcd[key]:\r
545 PcdSet[item] = Value\r
546\r
97fa0ee9 547 #Collect package set information from INF of FDF\r
a0a2cd1e
FB
548 PkgSet = set()\r
549 for Inf in ModuleList:\r
550 ModuleFile = PathClass(NormPath(Inf), GlobalData.gWorkspace, Arch)\r
551 if ModuleFile in Platform.Modules:\r
552 continue\r
553 ModuleData = self.BuildDatabase[ModuleFile, Arch, Target, Toolchain]\r
554 PkgSet.update(ModuleData.Packages)\r
555 Pkgs = list(PkgSet) + list(PGen.PackageList)\r
6b26dd71 556 DecPcds = set()\r
6f49996c 557 DecPcdsKey = set()\r
64b2609f 558 for Pkg in Pkgs:\r
25918452 559 for Pcd in Pkg.Pcds:\r
6b26dd71 560 DecPcds.add((Pcd[0], Pcd[1]))\r
4afd3d04 561 DecPcdsKey.add((Pcd[0], Pcd[1], Pcd[2]))\r
64b2609f 562\r
52302d4d 563 Platform.SkuName = self.SkuId\r
543f5ac3 564 for Name, Guid,Fileds in PcdSet:\r
64b2609f
LG
565 if (Name, Guid) not in DecPcds:\r
566 EdkLogger.error(\r
567 'build',\r
568 PARSER_ERROR,\r
569 "PCD (%s.%s) used in FDF is not declared in DEC files." % (Guid, Name),\r
570 File = self.FdfProfile.PcdFileLineDict[Name, Guid][0],\r
571 Line = self.FdfProfile.PcdFileLineDict[Name, Guid][1]\r
572 )\r
4afd3d04
LG
573 else:\r
574 # Check whether Dynamic or DynamicEx PCD used in FDF file. If used, build break and give a error message.\r
575 if (Name, Guid, TAB_PCDS_FIXED_AT_BUILD) in DecPcdsKey \\r
576 or (Name, Guid, TAB_PCDS_PATCHABLE_IN_MODULE) in DecPcdsKey \\r
577 or (Name, Guid, TAB_PCDS_FEATURE_FLAG) in DecPcdsKey:\r
4afd3d04
LG
578 continue\r
579 elif (Name, Guid, TAB_PCDS_DYNAMIC) in DecPcdsKey or (Name, Guid, TAB_PCDS_DYNAMIC_EX) in DecPcdsKey:\r
580 EdkLogger.error(\r
581 'build',\r
582 PARSER_ERROR,\r
583 "Using Dynamic or DynamicEx type of PCD [%s.%s] in FDF file is not allowed." % (Guid, Name),\r
584 File = self.FdfProfile.PcdFileLineDict[Name, Guid][0],\r
585 Line = self.FdfProfile.PcdFileLineDict[Name, Guid][1]\r
586 )\r
52302d4d
LG
587\r
588 Pa = PlatformAutoGen(self, self.MetaFile, Target, Toolchain, Arch)\r
589 #\r
590 # Explicitly collect platform's dynamic PCDs\r
591 #\r
592 Pa.CollectPlatformDynamicPcds()\r
2bc3256c 593 Pa.CollectFixedAtBuildPcds()\r
52302d4d 594 self.AutoGenObjectList.append(Pa)\r
47fea6af 595\r
36d083ef
YZ
596 #\r
597 # Generate Package level hash value\r
598 #\r
599 GlobalData.gPackageHash[Arch] = {}\r
600 if GlobalData.gUseHashCache:\r
601 for Pkg in Pkgs:\r
602 self._GenPkgLevelHash(Pkg)\r
603\r
6780eef1
LG
604 #\r
605 # Check PCDs token value conflict in each DEC file.\r
606 #\r
607 self._CheckAllPcdsTokenValueConflict()\r
47fea6af 608\r
4234283c
LG
609 #\r
610 # Check PCD type and definition between DSC and DEC\r
611 #\r
612 self._CheckPcdDefineAndType()\r
97fa0ee9 613\r
c17956e0 614 #\r
2d499388 615 # Create BuildOptions Macro & PCD metafile, also add the Active Platform and FDF file.\r
c17956e0
DL
616 #\r
617 content = 'gCommandLineDefines: '\r
618 content += str(GlobalData.gCommandLineDefines)\r
619 content += os.linesep\r
620 content += 'BuildOptionPcd: '\r
621 content += str(GlobalData.BuildOptionPcd)\r
2d499388
YZ
622 content += os.linesep\r
623 content += 'Active Platform: '\r
624 content += str(self.Platform)\r
625 content += os.linesep\r
626 if self.FdfFile:\r
627 content += 'Flash Image Definition: '\r
628 content += str(self.FdfFile)\r
36d083ef 629 content += os.linesep\r
c17956e0
DL
630 SaveFileOnChange(os.path.join(self.BuildDir, 'BuildOptions'), content, False)\r
631\r
99adfe9f
YZ
632 #\r
633 # Create PcdToken Number file for Dynamic/DynamicEx Pcd.\r
634 #\r
635 PcdTokenNumber = 'PcdTokenNumber: '\r
636 if Pa.PcdTokenNumber:\r
637 if Pa.DynamicPcdList:\r
638 for Pcd in Pa.DynamicPcdList:\r
639 PcdTokenNumber += os.linesep\r
640 PcdTokenNumber += str((Pcd.TokenCName, Pcd.TokenSpaceGuidCName))\r
641 PcdTokenNumber += ' : '\r
642 PcdTokenNumber += str(Pa.PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName])\r
643 SaveFileOnChange(os.path.join(self.BuildDir, 'PcdTokenNumber'), PcdTokenNumber, False)\r
644\r
c17956e0
DL
645 #\r
646 # Get set of workspace metafiles\r
647 #\r
648 AllWorkSpaceMetaFiles = self._GetMetaFiles(Target, Toolchain, Arch)\r
649\r
650 #\r
651 # Retrieve latest modified time of all metafiles\r
652 #\r
653 SrcTimeStamp = 0\r
654 for f in AllWorkSpaceMetaFiles:\r
655 if os.stat(f)[8] > SrcTimeStamp:\r
656 SrcTimeStamp = os.stat(f)[8]\r
657 self._SrcTimeStamp = SrcTimeStamp\r
658\r
36d083ef
YZ
659 if GlobalData.gUseHashCache:\r
660 m = hashlib.md5()\r
661 for files in AllWorkSpaceMetaFiles:\r
662 if files.endswith('.dec'):\r
663 continue\r
86e6cf98 664 f = open(files, 'rb')\r
36d083ef
YZ
665 Content = f.read()\r
666 f.close()\r
667 m.update(Content)\r
668 SaveFileOnChange(os.path.join(self.BuildDir, 'AutoGen.hash'), m.hexdigest(), True)\r
669 GlobalData.gPlatformHash = m.hexdigest()\r
670\r
c17956e0
DL
671 #\r
672 # Write metafile list to build directory\r
673 #\r
674 AutoGenFilePath = os.path.join(self.BuildDir, 'AutoGen')\r
675 if os.path.exists (AutoGenFilePath):\r
676 os.remove(AutoGenFilePath)\r
677 if not os.path.exists(self.BuildDir):\r
678 os.makedirs(self.BuildDir)\r
679 with open(os.path.join(self.BuildDir, 'AutoGen'), 'w+') as file:\r
680 for f in AllWorkSpaceMetaFiles:\r
72443dd2 681 print(f, file=file)\r
52302d4d
LG
682 return True\r
683\r
36d083ef 684 def _GenPkgLevelHash(self, Pkg):\r
3f34e36d
LD
685 if Pkg.PackageName in GlobalData.gPackageHash[Pkg.Arch]:\r
686 return\r
687\r
36d083ef
YZ
688 PkgDir = os.path.join(self.BuildDir, Pkg.Arch, Pkg.PackageName)\r
689 CreateDirectory(PkgDir)\r
690 HashFile = os.path.join(PkgDir, Pkg.PackageName + '.hash')\r
691 m = hashlib.md5()\r
692 # Get .dec file's hash value\r
86e6cf98 693 f = open(Pkg.MetaFile.Path, 'rb')\r
36d083ef
YZ
694 Content = f.read()\r
695 f.close()\r
696 m.update(Content)\r
697 # Get include files hash value\r
698 if Pkg.Includes:\r
3f34e36d 699 for inc in sorted(Pkg.Includes, key=lambda x: str(x)):\r
36d083ef 700 for Root, Dirs, Files in os.walk(str(inc)):\r
3f34e36d 701 for File in sorted(Files):\r
36d083ef 702 File_Path = os.path.join(Root, File)\r
86e6cf98 703 f = open(File_Path, 'rb')\r
36d083ef
YZ
704 Content = f.read()\r
705 f.close()\r
706 m.update(Content)\r
707 SaveFileOnChange(HashFile, m.hexdigest(), True)\r
3f34e36d 708 GlobalData.gPackageHash[Pkg.Arch][Pkg.PackageName] = m.hexdigest()\r
763e8edf 709\r
c17956e0
DL
710 def _GetMetaFiles(self, Target, Toolchain, Arch):\r
711 AllWorkSpaceMetaFiles = set()\r
712 #\r
713 # add fdf\r
714 #\r
715 if self.FdfFile:\r
716 AllWorkSpaceMetaFiles.add (self.FdfFile.Path)\r
caf74495
JC
717 for f in GlobalData.gFdfParser.GetAllIncludedFile():\r
718 AllWorkSpaceMetaFiles.add (f.FileName)\r
c17956e0
DL
719 #\r
720 # add dsc\r
721 #\r
722 AllWorkSpaceMetaFiles.add(self.MetaFile.Path)\r
723\r
724 #\r
86601b78
DL
725 # add build_rule.txt & tools_def.txt\r
726 #\r
51de5c30
YZ
727 AllWorkSpaceMetaFiles.add(os.path.join(GlobalData.gConfDirectory, gDefaultBuildRuleFile))\r
728 AllWorkSpaceMetaFiles.add(os.path.join(GlobalData.gConfDirectory, gDefaultToolsDefFile))\r
86601b78 729\r
c17956e0
DL
730 # add BuildOption metafile\r
731 #\r
732 AllWorkSpaceMetaFiles.add(os.path.join(self.BuildDir, 'BuildOptions'))\r
733\r
99adfe9f
YZ
734 # add PcdToken Number file for Dynamic/DynamicEx Pcd\r
735 #\r
736 AllWorkSpaceMetaFiles.add(os.path.join(self.BuildDir, 'PcdTokenNumber'))\r
737\r
c17956e0 738 for Arch in self.ArchList:\r
c17956e0
DL
739 #\r
740 # add dec\r
741 #\r
caf74495 742 for Package in PlatformAutoGen(self, self.MetaFile, Target, Toolchain, Arch).PackageList:\r
c17956e0
DL
743 AllWorkSpaceMetaFiles.add(Package.MetaFile.Path)\r
744\r
745 #\r
746 # add included dsc\r
747 #\r
caf74495 748 for filePath in self.BuildDatabase[self.MetaFile, Arch, Target, Toolchain]._RawData.IncludedFiles:\r
c17956e0
DL
749 AllWorkSpaceMetaFiles.add(filePath.Path)\r
750\r
751 return AllWorkSpaceMetaFiles\r
752\r
4234283c 753 def _CheckPcdDefineAndType(self):\r
caf74495
JC
754 PcdTypeSet = {TAB_PCDS_FIXED_AT_BUILD,\r
755 TAB_PCDS_PATCHABLE_IN_MODULE,\r
756 TAB_PCDS_FEATURE_FLAG,\r
757 TAB_PCDS_DYNAMIC,\r
758 TAB_PCDS_DYNAMIC_EX}\r
4234283c
LG
759\r
760 # This dict store PCDs which are not used by any modules with specified arches\r
9006a2c6 761 UnusedPcd = OrderedDict()\r
4234283c
LG
762 for Pa in self.AutoGenObjectList:\r
763 # Key of DSC's Pcds dictionary is PcdCName, TokenSpaceGuid\r
764 for Pcd in Pa.Platform.Pcds:\r
765 PcdType = Pa.Platform.Pcds[Pcd].Type\r
47fea6af 766\r
f7496d71 767 # If no PCD type, this PCD comes from FDF\r
4234283c
LG
768 if not PcdType:\r
769 continue\r
47fea6af 770\r
4234283c 771 # Try to remove Hii and Vpd suffix\r
6b1f2cf4
CJ
772 if PcdType.startswith(TAB_PCDS_DYNAMIC_EX):\r
773 PcdType = TAB_PCDS_DYNAMIC_EX\r
774 elif PcdType.startswith(TAB_PCDS_DYNAMIC):\r
775 PcdType = TAB_PCDS_DYNAMIC\r
47fea6af 776\r
4234283c
LG
777 for Package in Pa.PackageList:\r
778 # Key of DEC's Pcds dictionary is PcdCName, TokenSpaceGuid, PcdType\r
779 if (Pcd[0], Pcd[1], PcdType) in Package.Pcds:\r
780 break\r
caf74495 781 for Type in PcdTypeSet:\r
4234283c
LG
782 if (Pcd[0], Pcd[1], Type) in Package.Pcds:\r
783 EdkLogger.error(\r
784 'build',\r
785 FORMAT_INVALID,\r
786 "Type [%s] of PCD [%s.%s] in DSC file doesn't match the type [%s] defined in DEC file." \\r
787 % (Pa.Platform.Pcds[Pcd].Type, Pcd[1], Pcd[0], Type),\r
788 ExtraData=None\r
789 )\r
790 return\r
791 else:\r
792 UnusedPcd.setdefault(Pcd, []).append(Pa.Arch)\r
793\r
794 for Pcd in UnusedPcd:\r
795 EdkLogger.warn(\r
796 'build',\r
797 "The PCD was not specified by any INF module in the platform for the given architecture.\n"\r
798 "\tPCD: [%s.%s]\n\tPlatform: [%s]\n\tArch: %s"\r
799 % (Pcd[1], Pcd[0], os.path.basename(str(self.MetaFile)), str(UnusedPcd[Pcd])),\r
800 ExtraData=None\r
801 )\r
802\r
52302d4d
LG
803 def __repr__(self):\r
804 return "%s [%s]" % (self.MetaFile, ", ".join(self.ArchList))\r
805\r
806 ## Return the directory to store FV files\r
e6c62ab7
CJ
807 @cached_property\r
808 def FvDir(self):\r
809 return path.join(self.BuildDir, TAB_FV_DIRECTORY)\r
52302d4d
LG
810\r
811 ## Return the directory to store all intermediate and final files built\r
e6c62ab7
CJ
812 @cached_property\r
813 def BuildDir(self):\r
814 return self.AutoGenObjectList[0].BuildDir\r
52302d4d
LG
815\r
816 ## Return the build output directory platform specifies\r
e6c62ab7
CJ
817 @cached_property\r
818 def OutputDir(self):\r
52302d4d
LG
819 return self.Platform.OutputDirectory\r
820\r
821 ## Return platform name\r
e6c62ab7
CJ
822 @cached_property\r
823 def Name(self):\r
52302d4d
LG
824 return self.Platform.PlatformName\r
825\r
826 ## Return meta-file GUID\r
e6c62ab7
CJ
827 @cached_property\r
828 def Guid(self):\r
52302d4d
LG
829 return self.Platform.Guid\r
830\r
831 ## Return platform version\r
e6c62ab7
CJ
832 @cached_property\r
833 def Version(self):\r
52302d4d
LG
834 return self.Platform.Version\r
835\r
836 ## Return paths of tools\r
e6c62ab7
CJ
837 @cached_property\r
838 def ToolDefinition(self):\r
52302d4d
LG
839 return self.AutoGenObjectList[0].ToolDefinition\r
840\r
841 ## Return directory of platform makefile\r
842 #\r
843 # @retval string Makefile directory\r
844 #\r
e6c62ab7
CJ
845 @cached_property\r
846 def MakeFileDir(self):\r
847 return self.BuildDir\r
52302d4d
LG
848\r
849 ## Return build command string\r
850 #\r
851 # @retval string Build command string\r
852 #\r
e6c62ab7
CJ
853 @cached_property\r
854 def BuildCommand(self):\r
855 # BuildCommand should be all the same. So just get one from platform AutoGen\r
856 return self.AutoGenObjectList[0].BuildCommand\r
47fea6af 857\r
6780eef1
LG
858 ## Check the PCDs token value conflict in each DEC file.\r
859 #\r
860 # Will cause build break and raise error message while two PCDs conflict.\r
f7496d71 861 #\r
6780eef1
LG
862 # @return None\r
863 #\r
864 def _CheckAllPcdsTokenValueConflict(self):\r
b36d134f
LG
865 for Pa in self.AutoGenObjectList:\r
866 for Package in Pa.PackageList:\r
6780eef1 867 PcdList = Package.Pcds.values()\r
87010d3d 868 PcdList.sort(key=lambda x: int(x.TokenValue, 0))\r
6780eef1
LG
869 Count = 0\r
870 while (Count < len(PcdList) - 1) :\r
871 Item = PcdList[Count]\r
872 ItemNext = PcdList[Count + 1]\r
873 #\r
874 # Make sure in the same token space the TokenValue should be unique\r
875 #\r
f827cd07 876 if (int(Item.TokenValue, 0) == int(ItemNext.TokenValue, 0)):\r
6780eef1
LG
877 SameTokenValuePcdList = []\r
878 SameTokenValuePcdList.append(Item)\r
879 SameTokenValuePcdList.append(ItemNext)\r
880 RemainPcdListLength = len(PcdList) - Count - 2\r
881 for ValueSameCount in range(RemainPcdListLength):\r
f827cd07 882 if int(PcdList[len(PcdList) - RemainPcdListLength + ValueSameCount].TokenValue, 0) == int(Item.TokenValue, 0):\r
6780eef1
LG
883 SameTokenValuePcdList.append(PcdList[len(PcdList) - RemainPcdListLength + ValueSameCount])\r
884 else:\r
885 break;\r
886 #\r
887 # Sort same token value PCD list with TokenGuid and TokenCName\r
888 #\r
87010d3d 889 SameTokenValuePcdList.sort(key=lambda x: "%s.%s" % (x.TokenSpaceGuidCName, x.TokenCName))\r
47fea6af 890 SameTokenValuePcdListCount = 0\r
6780eef1 891 while (SameTokenValuePcdListCount < len(SameTokenValuePcdList) - 1):\r
2a29017e 892 Flag = False\r
47fea6af
YZ
893 TemListItem = SameTokenValuePcdList[SameTokenValuePcdListCount]\r
894 TemListItemNext = SameTokenValuePcdList[SameTokenValuePcdListCount + 1]\r
895\r
6780eef1 896 if (TemListItem.TokenSpaceGuidCName == TemListItemNext.TokenSpaceGuidCName) and (TemListItem.TokenCName != TemListItemNext.TokenCName):\r
2a29017e
YZ
897 for PcdItem in GlobalData.MixedPcd:\r
898 if (TemListItem.TokenCName, TemListItem.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem] or \\r
899 (TemListItemNext.TokenCName, TemListItemNext.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:\r
900 Flag = True\r
901 if not Flag:\r
902 EdkLogger.error(\r
903 'build',\r
904 FORMAT_INVALID,\r
905 "The TokenValue [%s] of PCD [%s.%s] is conflict with: [%s.%s] in %s"\\r
906 % (TemListItem.TokenValue, TemListItem.TokenSpaceGuidCName, TemListItem.TokenCName, TemListItemNext.TokenSpaceGuidCName, TemListItemNext.TokenCName, Package),\r
907 ExtraData=None\r
908 )\r
6780eef1
LG
909 SameTokenValuePcdListCount += 1\r
910 Count += SameTokenValuePcdListCount\r
911 Count += 1\r
47fea6af 912\r
6780eef1 913 PcdList = Package.Pcds.values()\r
87010d3d 914 PcdList.sort(key=lambda x: "%s.%s" % (x.TokenSpaceGuidCName, x.TokenCName))\r
6780eef1
LG
915 Count = 0\r
916 while (Count < len(PcdList) - 1) :\r
917 Item = PcdList[Count]\r
47fea6af 918 ItemNext = PcdList[Count + 1]\r
6780eef1
LG
919 #\r
920 # Check PCDs with same TokenSpaceGuidCName.TokenCName have same token value as well.\r
921 #\r
f827cd07 922 if (Item.TokenSpaceGuidCName == ItemNext.TokenSpaceGuidCName) and (Item.TokenCName == ItemNext.TokenCName) and (int(Item.TokenValue, 0) != int(ItemNext.TokenValue, 0)):\r
6780eef1
LG
923 EdkLogger.error(\r
924 'build',\r
925 FORMAT_INVALID,\r
926 "The TokenValue [%s] of PCD [%s.%s] in %s defined in two places should be same as well."\\r
927 % (Item.TokenValue, Item.TokenSpaceGuidCName, Item.TokenCName, Package),\r
928 ExtraData=None\r
929 )\r
930 Count += 1\r
97fa0ee9 931 ## Generate fds command\r
e6c62ab7
CJ
932 @property\r
933 def GenFdsCommand(self):\r
03af2753 934 return (GenMake.TopLevelMakefile(self)._TEMPLATE_.Replace(GenMake.TopLevelMakefile(self)._TemplateDict)).strip()\r
52302d4d 935\r
e56468c0 936 ## Create makefile for the platform and modules in it\r
52302d4d
LG
937 #\r
938 # @param CreateDepsMakeFile Flag indicating if the makefile for\r
939 # modules will be created as well\r
940 #\r
941 def CreateMakeFile(self, CreateDepsMakeFile=False):\r
caf74495
JC
942 if not CreateDepsMakeFile:\r
943 return\r
944 for Pa in self.AutoGenObjectList:\r
945 Pa.CreateMakeFile(True)\r
52302d4d
LG
946\r
947 ## Create autogen code for platform and modules\r
948 #\r
949 # Since there's no autogen code for platform, this method will do nothing\r
950 # if CreateModuleCodeFile is set to False.\r
951 #\r
952 # @param CreateDepsCodeFile Flag indicating if creating module's\r
953 # autogen code file or not\r
954 #\r
955 def CreateCodeFile(self, CreateDepsCodeFile=False):\r
956 if not CreateDepsCodeFile:\r
957 return\r
958 for Pa in self.AutoGenObjectList:\r
caf74495 959 Pa.CreateCodeFile(True)\r
52302d4d 960\r
7c1fd323
LG
961 ## Create AsBuilt INF file the platform\r
962 #\r
963 def CreateAsBuiltInf(self):\r
964 return\r
965\r
52302d4d
LG
966\r
967## AutoGen class for platform\r
968#\r
969# PlatformAutoGen class will process the original information in platform\r
970# file in order to generate makefile for platform.\r
971#\r
972class PlatformAutoGen(AutoGen):\r
b24e99f7
CJ
973 # call super().__init__ then call the worker function with different parameter count\r
974 def __init__(self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):\r
b23414f6 975 if not hasattr(self, "_Init"):\r
4ce4f757 976 super().__init__(self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)\r
b24e99f7
CJ
977 self._InitWorker(Workspace, MetaFile, Target, Toolchain, Arch)\r
978 self._Init = True\r
52302d4d 979 #\r
f7496d71 980 # Used to store all PCDs for both PEI and DXE phase, in order to generate\r
52302d4d 981 # correct PCD database\r
f7496d71 982 #\r
52302d4d
LG
983 _DynaPcdList_ = []\r
984 _NonDynaPcdList_ = []\r
61ee1dff 985 _PlatformPcds = {}\r
f7496d71 986\r
6780eef1 987 #\r
f7496d71 988 # The priority list while override build option\r
6780eef1
LG
989 #\r
990 PrioList = {"0x11111" : 16, # TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE (Highest)\r
991 "0x01111" : 15, # ******_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE\r
992 "0x10111" : 14, # TARGET_*********_ARCH_COMMANDTYPE_ATTRIBUTE\r
f7496d71 993 "0x00111" : 13, # ******_*********_ARCH_COMMANDTYPE_ATTRIBUTE\r
6780eef1
LG
994 "0x11011" : 12, # TARGET_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE\r
995 "0x01011" : 11, # ******_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE\r
996 "0x10011" : 10, # TARGET_*********_****_COMMANDTYPE_ATTRIBUTE\r
997 "0x00011" : 9, # ******_*********_****_COMMANDTYPE_ATTRIBUTE\r
998 "0x11101" : 8, # TARGET_TOOLCHAIN_ARCH_***********_ATTRIBUTE\r
999 "0x01101" : 7, # ******_TOOLCHAIN_ARCH_***********_ATTRIBUTE\r
1000 "0x10101" : 6, # TARGET_*********_ARCH_***********_ATTRIBUTE\r
1001 "0x00101" : 5, # ******_*********_ARCH_***********_ATTRIBUTE\r
1002 "0x11001" : 4, # TARGET_TOOLCHAIN_****_***********_ATTRIBUTE\r
1003 "0x01001" : 3, # ******_TOOLCHAIN_****_***********_ATTRIBUTE\r
1004 "0x10001" : 2, # TARGET_*********_****_***********_ATTRIBUTE\r
1005 "0x00001" : 1} # ******_*********_****_***********_ATTRIBUTE (Lowest)\r
47fea6af 1006\r
b24e99f7 1007 ## Initialize PlatformAutoGen\r
52302d4d 1008 #\r
52302d4d
LG
1009 #\r
1010 # @param Workspace WorkspaceAutoGen object\r
1011 # @param PlatformFile Platform file (DSC file)\r
1012 # @param Target Build target (DEBUG, RELEASE)\r
1013 # @param Toolchain Name of tool chain\r
1014 # @param Arch arch of the platform supports\r
1015 #\r
b24e99f7 1016 def _InitWorker(self, Workspace, PlatformFile, Target, Toolchain, Arch):\r
52302d4d
LG
1017 EdkLogger.debug(EdkLogger.DEBUG_9, "AutoGen platform [%s] [%s]" % (PlatformFile, Arch))\r
1018 GlobalData.gProcessingFile = "%s [%s, %s, %s]" % (PlatformFile, Arch, Toolchain, Target)\r
1019\r
1020 self.MetaFile = PlatformFile\r
1021 self.Workspace = Workspace\r
1022 self.WorkspaceDir = Workspace.WorkspaceDir\r
1023 self.ToolChain = Toolchain\r
1024 self.BuildTarget = Target\r
1025 self.Arch = Arch\r
1026 self.SourceDir = PlatformFile.SubDir\r
1027 self.SourceOverrideDir = None\r
1028 self.FdTargetList = self.Workspace.FdTargetList\r
1029 self.FvTargetList = self.Workspace.FvTargetList\r
1030 self.AllPcdList = []\r
a0a2cd1e
FB
1031 # get the original module/package/platform objects\r
1032 self.BuildDatabase = Workspace.BuildDatabase\r
8518bf0b 1033 self.DscBuildDataObj = Workspace.Platform\r
52302d4d
LG
1034\r
1035 # flag indicating if the makefile/C-code file has been created or not\r
1036 self.IsMakeFileCreated = False\r
e6eae3b4 1037\r
52302d4d
LG
1038 self._DynamicPcdList = None # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]\r
1039 self._NonDynamicPcdList = None # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]\r
e6eae3b4 1040\r
a0a2cd1e
FB
1041 self._AsBuildInfList = []\r
1042 self._AsBuildModuleList = []\r
47854fd5
LG
1043\r
1044 self.VariableInfo = None\r
1045\r
4231a819 1046 if GlobalData.gFdfParser is not None:\r
a0a2cd1e
FB
1047 self._AsBuildInfList = GlobalData.gFdfParser.Profile.InfList\r
1048 for Inf in self._AsBuildInfList:\r
1049 InfClass = PathClass(NormPath(Inf), GlobalData.gWorkspace, self.Arch)\r
1050 M = self.BuildDatabase[InfClass, self.Arch, self.BuildTarget, self.ToolChain]\r
f5f4667d 1051 if not M.IsBinaryModule:\r
a0a2cd1e
FB
1052 continue\r
1053 self._AsBuildModuleList.append(InfClass)\r
03af2753
HC
1054 # get library/modules for build\r
1055 self.LibraryBuildDirectoryList = []\r
1056 self.ModuleBuildDirectoryList = []\r
47854fd5 1057\r
52302d4d
LG
1058 return True\r
1059\r
e6eae3b4 1060 @cached_class_function\r
52302d4d
LG
1061 def __repr__(self):\r
1062 return "%s [%s]" % (self.MetaFile, self.Arch)\r
1063\r
1064 ## Create autogen code for platform and modules\r
1065 #\r
1066 # Since there's no autogen code for platform, this method will do nothing\r
1067 # if CreateModuleCodeFile is set to False.\r
1068 #\r
1069 # @param CreateModuleCodeFile Flag indicating if creating module's\r
1070 # autogen code file or not\r
1071 #\r
e6eae3b4 1072 @cached_class_function\r
52302d4d
LG
1073 def CreateCodeFile(self, CreateModuleCodeFile=False):\r
1074 # only module has code to be greated, so do nothing if CreateModuleCodeFile is False\r
e6eae3b4 1075 if not CreateModuleCodeFile:\r
52302d4d
LG
1076 return\r
1077\r
1078 for Ma in self.ModuleAutoGenList:\r
1079 Ma.CreateCodeFile(True)\r
1080\r
03af2753 1081 ## Generate Fds Command\r
e6eae3b4
CJ
1082 @cached_property\r
1083 def GenFdsCommand(self):\r
03af2753 1084 return self.Workspace.GenFdsCommand\r
481252bb 1085\r
4def57d9 1086 ## Create makefile for the platform and modules in it\r
52302d4d
LG
1087 #\r
1088 # @param CreateModuleMakeFile Flag indicating if the makefile for\r
1089 # modules will be created as well\r
1090 #\r
37de70b7 1091 def CreateMakeFile(self, CreateModuleMakeFile=False, FfsCommand = {}):\r
52302d4d 1092 if CreateModuleMakeFile:\r
4def57d9
CJ
1093 for Ma in self._MaList:\r
1094 key = (Ma.MetaFile.File, self.Arch)\r
1095 if key in FfsCommand:\r
1096 Ma.CreateMakeFile(True, FfsCommand[key])\r
37de70b7
YZ
1097 else:\r
1098 Ma.CreateMakeFile(True)\r
52302d4d
LG
1099\r
1100 # no need to create makefile for the platform more than once\r
1101 if self.IsMakeFileCreated:\r
1102 return\r
1103\r
03af2753 1104 # create library/module build dirs for platform\r
52302d4d 1105 Makefile = GenMake.PlatformMakefile(self)\r
03af2753
HC
1106 self.LibraryBuildDirectoryList = Makefile.GetLibraryBuildDirectoryList()\r
1107 self.ModuleBuildDirectoryList = Makefile.GetModuleBuildDirectoryList()\r
1108\r
52302d4d
LG
1109 self.IsMakeFileCreated = True\r
1110\r
2bc3256c
LG
1111 ## Deal with Shared FixedAtBuild Pcds\r
1112 #\r
1113 def CollectFixedAtBuildPcds(self):\r
1114 for LibAuto in self.LibraryAutoGenList:\r
f7496d71
LG
1115 FixedAtBuildPcds = {}\r
1116 ShareFixedAtBuildPcdsSameValue = {}\r
b23414f6 1117 for Module in LibAuto.ReferenceModules:\r
d900d7c9 1118 for Pcd in set(Module.FixedAtBuildPcds + LibAuto.FixedAtBuildPcds):\r
9edba51f
YZ
1119 DefaultValue = Pcd.DefaultValue\r
1120 # Cover the case: DSC component override the Pcd value and the Pcd only used in one Lib\r
1121 if Pcd in Module.LibraryPcdList:\r
1122 Index = Module.LibraryPcdList.index(Pcd)\r
1123 DefaultValue = Module.LibraryPcdList[Index].DefaultValue\r
ccaa7754 1124 key = ".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName))\r
2bc3256c
LG
1125 if key not in FixedAtBuildPcds:\r
1126 ShareFixedAtBuildPcdsSameValue[key] = True\r
9edba51f 1127 FixedAtBuildPcds[key] = DefaultValue\r
2bc3256c 1128 else:\r
9edba51f 1129 if FixedAtBuildPcds[key] != DefaultValue:\r
f7496d71 1130 ShareFixedAtBuildPcdsSameValue[key] = False\r
2bc3256c 1131 for Pcd in LibAuto.FixedAtBuildPcds:\r
ccaa7754
GL
1132 key = ".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName))\r
1133 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) not in self.NonDynamicPcdDict:\r
2bc3256c
LG
1134 continue\r
1135 else:\r
ccaa7754 1136 DscPcd = self.NonDynamicPcdDict[(Pcd.TokenCName, Pcd.TokenSpaceGuidCName)]\r
6b1f2cf4 1137 if DscPcd.Type != TAB_PCDS_FIXED_AT_BUILD:\r
2bc3256c 1138 continue\r
f7496d71 1139 if key in ShareFixedAtBuildPcdsSameValue and ShareFixedAtBuildPcdsSameValue[key]:\r
eca980c0 1140 LibAuto.ConstPcd[key] = FixedAtBuildPcds[key]\r
2bc3256c 1141\r
34952f49 1142 def CollectVariables(self, DynamicPcdSet):\r
47854fd5
LG
1143 VpdRegionSize = 0\r
1144 VpdRegionBase = 0\r
1145 if self.Workspace.FdfFile:\r
1146 FdDict = self.Workspace.FdfProfile.FdDict[GlobalData.gFdfParser.CurrentFdName]\r
1147 for FdRegion in FdDict.RegionList:\r
1148 for item in FdRegion.RegionDataList:\r
1149 if self.Platform.VpdToolGuid.strip() and self.Platform.VpdToolGuid in item:\r
1150 VpdRegionSize = FdRegion.Size\r
1151 VpdRegionBase = FdRegion.Offset\r
1152 break\r
1153\r
f27e800a 1154 VariableInfo = VariableMgr(self.DscBuildDataObj._GetDefaultStores(), self.DscBuildDataObj.SkuIds)\r
47854fd5
LG
1155 VariableInfo.SetVpdRegionMaxSize(VpdRegionSize)\r
1156 VariableInfo.SetVpdRegionOffset(VpdRegionBase)\r
34952f49
LG
1157 Index = 0\r
1158 for Pcd in DynamicPcdSet:\r
ccaa7754 1159 pcdname = ".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName))\r
8518bf0b
LG
1160 for SkuName in Pcd.SkuInfoList:\r
1161 Sku = Pcd.SkuInfoList[SkuName]\r
1162 SkuId = Sku.SkuId\r
4231a819 1163 if SkuId is None or SkuId == '':\r
8518bf0b
LG
1164 continue\r
1165 if len(Sku.VariableName) > 0:\r
1166 VariableGuidStructure = Sku.VariableGuidValue\r
1167 VariableGuid = GuidStructureStringToGuidString(VariableGuidStructure)\r
a3623244 1168 for StorageName in Sku.DefaultStoreDict:\r
6a147d6d 1169 VariableInfo.append_variable(var_info(Index, pcdname, StorageName, SkuName, StringToArray(Sku.VariableName), VariableGuid, Sku.VariableOffset, Sku.VariableAttribute, Sku.HiiDefaultValue, Sku.DefaultStoreDict[StorageName], Pcd.DatumType, Pcd.CustomAttribute['DscPosition'], Pcd.CustomAttribute.get('IsStru',False)))\r
34952f49
LG
1170 Index += 1\r
1171 return VariableInfo\r
47854fd5 1172\r
ccaa7754 1173 def UpdateNVStoreMaxSize(self, OrgVpdFile):\r
0b6c5954 1174 if self.VariableInfo:\r
91fa33ee 1175 VpdMapFilePath = os.path.join(self.BuildDir, TAB_FV_DIRECTORY, "%s.map" % self.Platform.VpdToolGuid)\r
0b6c5954
LG
1176 PcdNvStoreDfBuffer = [item for item in self._DynamicPcdList if item.TokenCName == "PcdNvStoreDefaultValueBuffer" and item.TokenSpaceGuidCName == "gEfiMdeModulePkgTokenSpaceGuid"]\r
1177\r
1178 if PcdNvStoreDfBuffer:\r
1179 if os.path.exists(VpdMapFilePath):\r
1180 OrgVpdFile.Read(VpdMapFilePath)\r
1181 PcdItems = OrgVpdFile.GetOffset(PcdNvStoreDfBuffer[0])\r
8ac16789 1182 NvStoreOffset = PcdItems.values()[0].strip() if PcdItems else '0'\r
0b6c5954
LG
1183 else:\r
1184 EdkLogger.error("build", FILE_READ_FAILURE, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath)\r
1185\r
ccaa7754 1186 NvStoreOffset = int(NvStoreOffset, 16) if NvStoreOffset.upper().startswith("0X") else int(NvStoreOffset)\r
55c84777 1187 default_skuobj = PcdNvStoreDfBuffer[0].SkuInfoList.get(TAB_DEFAULT)\r
0b6c5954
LG
1188 maxsize = self.VariableInfo.VpdRegionSize - NvStoreOffset if self.VariableInfo.VpdRegionSize else len(default_skuobj.DefaultValue.split(","))\r
1189 var_data = self.VariableInfo.PatchNVStoreDefaultMaxSize(maxsize)\r
1190\r
1191 if var_data and default_skuobj:\r
1192 default_skuobj.DefaultValue = var_data\r
1193 PcdNvStoreDfBuffer[0].DefaultValue = var_data\r
1194 PcdNvStoreDfBuffer[0].SkuInfoList.clear()\r
55c84777 1195 PcdNvStoreDfBuffer[0].SkuInfoList[TAB_DEFAULT] = default_skuobj\r
0b6c5954 1196 PcdNvStoreDfBuffer[0].MaxDatumSize = str(len(default_skuobj.DefaultValue.split(",")))\r
47854fd5
LG
1197\r
1198 return OrgVpdFile\r
1199\r
52302d4d
LG
1200 ## Collect dynamic PCDs\r
1201 #\r
1202 # Gather dynamic PCDs list from each module and their settings from platform\r
1203 # This interface should be invoked explicitly when platform action is created.\r
1204 #\r
1205 def CollectPlatformDynamicPcds(self):\r
2a29017e
YZ
1206 for key in self.Platform.Pcds:\r
1207 for SinglePcd in GlobalData.MixedPcd:\r
1208 if (self.Platform.Pcds[key].TokenCName, self.Platform.Pcds[key].TokenSpaceGuidCName) == SinglePcd:\r
1209 for item in GlobalData.MixedPcd[SinglePcd]:\r
1210 Pcd_Type = item[0].split('_')[-1]\r
eece4292
CJ
1211 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 \\r
1212 (Pcd_Type == TAB_PCDS_DYNAMIC and self.Platform.Pcds[key].Type in PCD_DYNAMIC_TYPE_SET):\r
2a29017e
YZ
1213 Value = self.Platform.Pcds[key]\r
1214 Value.TokenCName = self.Platform.Pcds[key].TokenCName + '_' + Pcd_Type\r
1215 if len(key) == 2:\r
1216 newkey = (Value.TokenCName, key[1])\r
1217 elif len(key) == 3:\r
1218 newkey = (Value.TokenCName, key[1], key[2])\r
1219 del self.Platform.Pcds[key]\r
1220 self.Platform.Pcds[newkey] = Value\r
1221 break\r
2a29017e 1222 break\r
2a29017e 1223\r
52302d4d
LG
1224 # for gathering error information\r
1225 NoDatumTypePcdList = set()\r
a0a2cd1e
FB
1226 FdfModuleList = []\r
1227 for InfName in self._AsBuildInfList:\r
05cc51ad 1228 InfName = mws.join(self.WorkspaceDir, InfName)\r
a0a2cd1e 1229 FdfModuleList.append(os.path.normpath(InfName))\r
4def57d9
CJ
1230 for M in self._MaList:\r
1231# F is the Module for which M is the module autogen\r
47fea6af 1232 for PcdFromModule in M.ModulePcdList + M.LibraryPcdList:\r
52302d4d 1233 # make sure that the "VOID*" kind of datum has MaxDatumSize set\r
c93356ad 1234 if PcdFromModule.DatumType == TAB_VOID and not PcdFromModule.MaxDatumSize:\r
4def57d9 1235 NoDatumTypePcdList.add("%s.%s [%s]" % (PcdFromModule.TokenSpaceGuidCName, PcdFromModule.TokenCName, M.MetaFile))\r
52302d4d 1236\r
97fa0ee9 1237 # Check the PCD from Binary INF or Source INF\r
a0a2cd1e
FB
1238 if M.IsBinaryModule == True:\r
1239 PcdFromModule.IsFromBinaryInf = True\r
97fa0ee9 1240\r
f7496d71 1241 # Check the PCD from DSC or not\r
9eb87141
CJ
1242 PcdFromModule.IsFromDsc = (PcdFromModule.TokenCName, PcdFromModule.TokenSpaceGuidCName) in self.Platform.Pcds\r
1243\r
eece4292 1244 if PcdFromModule.Type in PCD_DYNAMIC_TYPE_SET or PcdFromModule.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
4def57d9 1245 if M.MetaFile.Path not in FdfModuleList:\r
f7496d71
LG
1246 # If one of the Source built modules listed in the DSC is not listed\r
1247 # in FDF modules, and the INF lists a PCD can only use the PcdsDynamic\r
1248 # access method (it is only listed in the DEC file that declares the\r
a0a2cd1e 1249 # PCD as PcdsDynamic), then build tool will report warning message\r
f7496d71
LG
1250 # notify the PI that they are attempting to build a module that must\r
1251 # be included in a flash image in order to be functional. These Dynamic\r
1252 # PCD will not be added into the Database unless it is used by other\r
a0a2cd1e 1253 # modules that are included in the FDF file.\r
eece4292 1254 if PcdFromModule.Type in PCD_DYNAMIC_TYPE_SET and \\r
a0a2cd1e
FB
1255 PcdFromModule.IsFromBinaryInf == False:\r
1256 # Print warning message to let the developer make a determine.\r
a0a2cd1e 1257 continue\r
f7496d71
LG
1258 # If one of the Source built modules listed in the DSC is not listed in\r
1259 # FDF modules, and the INF lists a PCD can only use the PcdsDynamicEx\r
1260 # access method (it is only listed in the DEC file that declares the\r
1261 # PCD as PcdsDynamicEx), then DO NOT break the build; DO NOT add the\r
a0a2cd1e 1262 # PCD to the Platform's PCD Database.\r
eece4292 1263 if PcdFromModule.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
a0a2cd1e 1264 continue\r
52302d4d
LG
1265 #\r
1266 # If a dynamic PCD used by a PEM module/PEI module & DXE module,\r
1267 # it should be stored in Pcd PEI database, If a dynamic only\r
1268 # used by DXE module, it should be stored in DXE PCD database.\r
1269 # The default Phase is DXE\r
1270 #\r
88c6c1b6 1271 if M.ModuleType in SUP_MODULE_SET_PEI:\r
52302d4d
LG
1272 PcdFromModule.Phase = "PEI"\r
1273 if PcdFromModule not in self._DynaPcdList_:\r
1274 self._DynaPcdList_.append(PcdFromModule)\r
1275 elif PcdFromModule.Phase == 'PEI':\r
1276 # overwrite any the same PCD existing, if Phase is PEI\r
1277 Index = self._DynaPcdList_.index(PcdFromModule)\r
1278 self._DynaPcdList_[Index] = PcdFromModule\r
1279 elif PcdFromModule not in self._NonDynaPcdList_:\r
1280 self._NonDynaPcdList_.append(PcdFromModule)\r
a0a2cd1e
FB
1281 elif PcdFromModule in self._NonDynaPcdList_ and PcdFromModule.IsFromBinaryInf == True:\r
1282 Index = self._NonDynaPcdList_.index(PcdFromModule)\r
1283 if self._NonDynaPcdList_[Index].IsFromBinaryInf == False:\r
1284 #The PCD from Binary INF will override the same one from source INF\r
1285 self._NonDynaPcdList_.remove (self._NonDynaPcdList_[Index])\r
1286 PcdFromModule.Pending = False\r
1287 self._NonDynaPcdList_.append (PcdFromModule)\r
1563349a 1288 DscModuleSet = {os.path.normpath(ModuleInf.Path) for ModuleInf in self.Platform.Modules}\r
f7496d71 1289 # add the PCD from modules that listed in FDF but not in DSC to Database\r
a0a2cd1e 1290 for InfName in FdfModuleList:\r
1563349a 1291 if InfName not in DscModuleSet:\r
a0a2cd1e
FB
1292 InfClass = PathClass(InfName)\r
1293 M = self.BuildDatabase[InfClass, self.Arch, self.BuildTarget, self.ToolChain]\r
f7496d71
LG
1294 # If a module INF in FDF but not in current arch's DSC module list, it must be module (either binary or source)\r
1295 # for different Arch. PCDs in source module for different Arch is already added before, so skip the source module here.\r
1296 # For binary module, if in current arch, we need to list the PCDs into database.\r
f5f4667d 1297 if not M.IsBinaryModule:\r
a0a2cd1e
FB
1298 continue\r
1299 # Override the module PCD setting by platform setting\r
1300 ModulePcdList = self.ApplyPcdSetting(M, M.Pcds)\r
1301 for PcdFromModule in ModulePcdList:\r
1302 PcdFromModule.IsFromBinaryInf = True\r
1303 PcdFromModule.IsFromDsc = False\r
1304 # Only allow the DynamicEx and Patchable PCD in AsBuild INF\r
eece4292 1305 if PcdFromModule.Type not in PCD_DYNAMIC_EX_TYPE_SET and PcdFromModule.Type not in TAB_PCDS_PATCHABLE_IN_MODULE:\r
a0a2cd1e
FB
1306 EdkLogger.error("build", AUTOGEN_ERROR, "PCD setting error",\r
1307 File=self.MetaFile,\r
1308 ExtraData="\n\tExisted %s PCD %s in:\n\t\t%s\n"\r
1309 % (PcdFromModule.Type, PcdFromModule.TokenCName, InfName))\r
1310 # make sure that the "VOID*" kind of datum has MaxDatumSize set\r
c93356ad 1311 if PcdFromModule.DatumType == TAB_VOID and not PcdFromModule.MaxDatumSize:\r
a0a2cd1e 1312 NoDatumTypePcdList.add("%s.%s [%s]" % (PcdFromModule.TokenSpaceGuidCName, PcdFromModule.TokenCName, InfName))\r
88c6c1b6 1313 if M.ModuleType in SUP_MODULE_SET_PEI:\r
a0a2cd1e 1314 PcdFromModule.Phase = "PEI"\r
eece4292 1315 if PcdFromModule not in self._DynaPcdList_ and PcdFromModule.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
a0a2cd1e
FB
1316 self._DynaPcdList_.append(PcdFromModule)\r
1317 elif PcdFromModule not in self._NonDynaPcdList_ and PcdFromModule.Type in TAB_PCDS_PATCHABLE_IN_MODULE:\r
1318 self._NonDynaPcdList_.append(PcdFromModule)\r
eece4292 1319 if PcdFromModule in self._DynaPcdList_ and PcdFromModule.Phase == 'PEI' and PcdFromModule.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
97fa0ee9 1320 # Overwrite the phase of any the same PCD existing, if Phase is PEI.\r
f7496d71 1321 # It is to solve the case that a dynamic PCD used by a PEM module/PEI\r
97fa0ee9
YL
1322 # module & DXE module at a same time.\r
1323 # Overwrite the type of the PCDs in source INF by the type of AsBuild\r
f7496d71 1324 # INF file as DynamicEx.\r
a0a2cd1e
FB
1325 Index = self._DynaPcdList_.index(PcdFromModule)\r
1326 self._DynaPcdList_[Index].Phase = PcdFromModule.Phase\r
1327 self._DynaPcdList_[Index].Type = PcdFromModule.Type\r
1328 for PcdFromModule in self._NonDynaPcdList_:\r
f7496d71
LG
1329 # If a PCD is not listed in the DSC file, but binary INF files used by\r
1330 # this platform all (that use this PCD) list the PCD in a [PatchPcds]\r
1331 # section, AND all source INF files used by this platform the build\r
1332 # that use the PCD list the PCD in either a [Pcds] or [PatchPcds]\r
a0a2cd1e 1333 # section, then the tools must NOT add the PCD to the Platform's PCD\r
f7496d71 1334 # Database; the build must assign the access method for this PCD as\r
a0a2cd1e
FB
1335 # PcdsPatchableInModule.\r
1336 if PcdFromModule not in self._DynaPcdList_:\r
1337 continue\r
1338 Index = self._DynaPcdList_.index(PcdFromModule)\r
1339 if PcdFromModule.IsFromDsc == False and \\r
1340 PcdFromModule.Type in TAB_PCDS_PATCHABLE_IN_MODULE and \\r
1341 PcdFromModule.IsFromBinaryInf == True and \\r
1342 self._DynaPcdList_[Index].IsFromBinaryInf == False:\r
1343 Index = self._DynaPcdList_.index(PcdFromModule)\r
1344 self._DynaPcdList_.remove (self._DynaPcdList_[Index])\r
52302d4d
LG
1345\r
1346 # print out error information and break the build, if error found\r
1347 if len(NoDatumTypePcdList) > 0:\r
1348 NoDatumTypePcdListString = "\n\t\t".join(NoDatumTypePcdList)\r
1349 EdkLogger.error("build", AUTOGEN_ERROR, "PCD setting error",\r
1350 File=self.MetaFile,\r
1351 ExtraData="\n\tPCD(s) without MaxDatumSize:\n\t\t%s\n"\r
1352 % NoDatumTypePcdListString)\r
1353 self._NonDynamicPcdList = self._NonDynaPcdList_\r
1354 self._DynamicPcdList = self._DynaPcdList_\r
52302d4d
LG
1355 #\r
1356 # Sort dynamic PCD list to:\r
f7496d71 1357 # 1) If PCD's datum type is VOID* and value is unicode string which starts with L, the PCD item should\r
52302d4d
LG
1358 # try to be put header of dynamicd List\r
1359 # 2) If PCD is HII type, the PCD item should be put after unicode type PCD\r
1360 #\r
1361 # The reason of sorting is make sure the unicode string is in double-byte alignment in string table.\r
1362 #\r
0b6c5954
LG
1363 UnicodePcdArray = set()\r
1364 HiiPcdArray = set()\r
1365 OtherPcdArray = set()\r
6780eef1 1366 VpdPcdDict = {}\r
e56468c0 1367 VpdFile = VpdInfoFile.VpdInfoFile()\r
61ee1dff
YZ
1368 NeedProcessVpdMapFile = False\r
1369\r
9eb87141
CJ
1370 for pcd in self.Platform.Pcds:\r
1371 if pcd not in self._PlatformPcds:\r
61ee1dff
YZ
1372 self._PlatformPcds[pcd] = self.Platform.Pcds[pcd]\r
1373\r
ae7b6df8
LG
1374 for item in self._PlatformPcds:\r
1375 if self._PlatformPcds[item].DatumType and self._PlatformPcds[item].DatumType not in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64, TAB_VOID, "BOOLEAN"]:\r
656d2539 1376 self._PlatformPcds[item].DatumType = TAB_VOID\r
ae7b6df8 1377\r
f7496d71 1378 if (self.Workspace.ArchList[-1] == self.Arch):\r
e56468c0 1379 for Pcd in self._DynamicPcdList:\r
e56468c0 1380 # just pick the a value to determine whether is unicode string type\r
9eb87141 1381 Sku = Pcd.SkuInfoList.values()[0]\r
e56468c0 1382 Sku.VpdOffset = Sku.VpdOffset.strip()\r
47fea6af 1383\r
ae7b6df8 1384 if Pcd.DatumType not in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64, TAB_VOID, "BOOLEAN"]:\r
656d2539 1385 Pcd.DatumType = TAB_VOID\r
ae7b6df8 1386\r
e56468c0 1387 # if found PCD which datum value is unicode string the insert to left size of UnicodeIndex\r
e56468c0 1388 # if found HII type PCD then insert to right of UnicodeIndex\r
e56468c0 1389 if Pcd.Type in [TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_VPD]:\r
47fea6af
YZ
1390 VpdPcdDict[(Pcd.TokenCName, Pcd.TokenSpaceGuidCName)] = Pcd\r
1391\r
34952f49 1392 #Collect DynamicHii PCD values and assign it to DynamicExVpd PCD gEfiMdeModulePkgTokenSpaceGuid.PcdNvStoreDefaultValueBuffer\r
ccaa7754 1393 PcdNvStoreDfBuffer = VpdPcdDict.get(("PcdNvStoreDefaultValueBuffer", "gEfiMdeModulePkgTokenSpaceGuid"))\r
34952f49 1394 if PcdNvStoreDfBuffer:\r
47854fd5 1395 self.VariableInfo = self.CollectVariables(self._DynamicPcdList)\r
47854fd5 1396 vardump = self.VariableInfo.dump()\r
626bece4 1397 if vardump:\r
2b8a6c44 1398 PcdNvStoreDfBuffer.DefaultValue = vardump\r
626bece4
LG
1399 for skuname in PcdNvStoreDfBuffer.SkuInfoList:\r
1400 PcdNvStoreDfBuffer.SkuInfoList[skuname].DefaultValue = vardump\r
1401 PcdNvStoreDfBuffer.MaxDatumSize = str(len(vardump.split(",")))\r
ced86858
ZZ
1402 else:\r
1403 #If the end user define [DefaultStores] and [XXX.Menufacturing] in DSC, but forget to configure PcdNvStoreDefaultValueBuffer to PcdsDynamicVpd\r
1404 if [Pcd for Pcd in self._DynamicPcdList if Pcd.UserDefinedDefaultStoresFlag]:\r
1405 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)\r
caf74495 1406 PlatformPcds = sorted(self._PlatformPcds.keys())\r
6780eef1
LG
1407 #\r
1408 # Add VPD type PCD into VpdFile and determine whether the VPD PCD need to be fixed up.\r
1409 #\r
626bece4 1410 VpdSkuMap = {}\r
6780eef1 1411 for PcdKey in PlatformPcds:\r
61ee1dff 1412 Pcd = self._PlatformPcds[PcdKey]\r
e8a47801
LG
1413 if Pcd.Type in [TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_VPD] and \\r
1414 PcdKey in VpdPcdDict:\r
1415 Pcd = VpdPcdDict[PcdKey]\r
626bece4 1416 SkuValueMap = {}\r
55c84777 1417 DefaultSku = Pcd.SkuInfoList.get(TAB_DEFAULT)\r
8ac16789
LG
1418 if DefaultSku:\r
1419 PcdValue = DefaultSku.DefaultValue\r
1420 if PcdValue not in SkuValueMap:\r
1421 SkuValueMap[PcdValue] = []\r
ccaa7754 1422 VpdFile.Add(Pcd, TAB_DEFAULT, DefaultSku.VpdOffset)\r
8ac16789
LG
1423 SkuValueMap[PcdValue].append(DefaultSku)\r
1424\r
ccaa7754 1425 for (SkuName, Sku) in Pcd.SkuInfoList.items():\r
e8a47801 1426 Sku.VpdOffset = Sku.VpdOffset.strip()\r
5a13737a
YZ
1427 PcdValue = Sku.DefaultValue\r
1428 if PcdValue == "":\r
1429 PcdValue = Pcd.DefaultValue\r
1430 if Sku.VpdOffset != '*':\r
1431 if PcdValue.startswith("{"):\r
1432 Alignment = 8\r
1433 elif PcdValue.startswith("L"):\r
1434 Alignment = 2\r
1435 else:\r
1436 Alignment = 1\r
ca85291f
YZ
1437 try:\r
1438 VpdOffset = int(Sku.VpdOffset)\r
1439 except:\r
1440 try:\r
1441 VpdOffset = int(Sku.VpdOffset, 16)\r
1442 except:\r
1443 EdkLogger.error("build", FORMAT_INVALID, "Invalid offset value %s for PCD %s.%s." % (Sku.VpdOffset, Pcd.TokenSpaceGuidCName, Pcd.TokenCName))\r
1444 if VpdOffset % Alignment != 0:\r
815ada26
YZ
1445 if PcdValue.startswith("{"):\r
1446 EdkLogger.warn("build", "The offset value of PCD %s.%s is not 8-byte aligned!" %(Pcd.TokenSpaceGuidCName, Pcd.TokenCName), File=self.MetaFile)\r
1447 else:\r
1448 EdkLogger.error("build", FORMAT_INVALID, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName, Alignment))\r
626bece4
LG
1449 if PcdValue not in SkuValueMap:\r
1450 SkuValueMap[PcdValue] = []\r
ccaa7754 1451 VpdFile.Add(Pcd, SkuName, Sku.VpdOffset)\r
626bece4 1452 SkuValueMap[PcdValue].append(Sku)\r
e8a47801
LG
1453 # if the offset of a VPD is *, then it need to be fixed up by third party tool.\r
1454 if not NeedProcessVpdMapFile and Sku.VpdOffset == "*":\r
1455 NeedProcessVpdMapFile = True\r
4231a819 1456 if self.Platform.VpdToolGuid is None or self.Platform.VpdToolGuid == '':\r
e8a47801
LG
1457 EdkLogger.error("Build", FILE_NOT_FOUND, \\r
1458 "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.")\r
47fea6af 1459\r
626bece4 1460 VpdSkuMap[PcdKey] = SkuValueMap\r
e56468c0 1461 #\r
1462 # Fix the PCDs define in VPD PCD section that never referenced by module.\r
1463 # An example is PCD for signature usage.\r
f7496d71 1464 #\r
6780eef1 1465 for DscPcd in PlatformPcds:\r
61ee1dff 1466 DscPcdEntry = self._PlatformPcds[DscPcd]\r
e56468c0 1467 if DscPcdEntry.Type in [TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_VPD]:\r
4231a819 1468 if not (self.Platform.VpdToolGuid is None or self.Platform.VpdToolGuid == ''):\r
e56468c0 1469 FoundFlag = False\r
9eb87141 1470 for VpdPcd in VpdFile._VpdArray:\r
e56468c0 1471 # This PCD has been referenced by module\r
1472 if (VpdPcd.TokenSpaceGuidCName == DscPcdEntry.TokenSpaceGuidCName) and \\r
1473 (VpdPcd.TokenCName == DscPcdEntry.TokenCName):\r
1474 FoundFlag = True\r
47fea6af 1475\r
e56468c0 1476 # Not found, it should be signature\r
1477 if not FoundFlag :\r
1478 # just pick the a value to determine whether is unicode string type\r
626bece4 1479 SkuValueMap = {}\r
e827d21d 1480 SkuObjList = DscPcdEntry.SkuInfoList.items()\r
55c84777 1481 DefaultSku = DscPcdEntry.SkuInfoList.get(TAB_DEFAULT)\r
8ac16789 1482 if DefaultSku:\r
ccaa7754
GL
1483 defaultindex = SkuObjList.index((TAB_DEFAULT, DefaultSku))\r
1484 SkuObjList[0], SkuObjList[defaultindex] = SkuObjList[defaultindex], SkuObjList[0]\r
1485 for (SkuName, Sku) in SkuObjList:\r
f7496d71
LG
1486 Sku.VpdOffset = Sku.VpdOffset.strip()\r
1487\r
e8a47801
LG
1488 # Need to iterate DEC pcd information to get the value & datumtype\r
1489 for eachDec in self.PackageList:\r
1490 for DecPcd in eachDec.Pcds:\r
1491 DecPcdEntry = eachDec.Pcds[DecPcd]\r
1492 if (DecPcdEntry.TokenSpaceGuidCName == DscPcdEntry.TokenSpaceGuidCName) and \\r
1493 (DecPcdEntry.TokenCName == DscPcdEntry.TokenCName):\r
1494 # Print warning message to let the developer make a determine.\r
1495 EdkLogger.warn("build", "Unreferenced vpd pcd used!",\r
1496 File=self.MetaFile, \\r
1497 ExtraData = "PCD: %s.%s used in the DSC file %s is unreferenced." \\r
f7496d71
LG
1498 %(DscPcdEntry.TokenSpaceGuidCName, DscPcdEntry.TokenCName, self.Platform.MetaFile.Path))\r
1499\r
e8a47801
LG
1500 DscPcdEntry.DatumType = DecPcdEntry.DatumType\r
1501 DscPcdEntry.DefaultValue = DecPcdEntry.DefaultValue\r
1502 DscPcdEntry.TokenValue = DecPcdEntry.TokenValue\r
1503 DscPcdEntry.TokenSpaceGuidValue = eachDec.Guids[DecPcdEntry.TokenSpaceGuidCName]\r
1504 # Only fix the value while no value provided in DSC file.\r
128d435f 1505 if not Sku.DefaultValue:\r
e8a47801 1506 DscPcdEntry.SkuInfoList[DscPcdEntry.SkuInfoList.keys()[0]].DefaultValue = DecPcdEntry.DefaultValue\r
f7496d71 1507\r
e8a47801
LG
1508 if DscPcdEntry not in self._DynamicPcdList:\r
1509 self._DynamicPcdList.append(DscPcdEntry)\r
e8a47801
LG
1510 Sku.VpdOffset = Sku.VpdOffset.strip()\r
1511 PcdValue = Sku.DefaultValue\r
5a13737a
YZ
1512 if PcdValue == "":\r
1513 PcdValue = DscPcdEntry.DefaultValue\r
1514 if Sku.VpdOffset != '*':\r
1515 if PcdValue.startswith("{"):\r
1516 Alignment = 8\r
1517 elif PcdValue.startswith("L"):\r
1518 Alignment = 2\r
1519 else:\r
1520 Alignment = 1\r
ca85291f
YZ
1521 try:\r
1522 VpdOffset = int(Sku.VpdOffset)\r
1523 except:\r
1524 try:\r
1525 VpdOffset = int(Sku.VpdOffset, 16)\r
1526 except:\r
1527 EdkLogger.error("build", FORMAT_INVALID, "Invalid offset value %s for PCD %s.%s." % (Sku.VpdOffset, DscPcdEntry.TokenSpaceGuidCName, DscPcdEntry.TokenCName))\r
1528 if VpdOffset % Alignment != 0:\r
815ada26
YZ
1529 if PcdValue.startswith("{"):\r
1530 EdkLogger.warn("build", "The offset value of PCD %s.%s is not 8-byte aligned!" %(DscPcdEntry.TokenSpaceGuidCName, DscPcdEntry.TokenCName), File=self.MetaFile)\r
1531 else:\r
1532 EdkLogger.error("build", FORMAT_INVALID, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (DscPcdEntry.TokenSpaceGuidCName, DscPcdEntry.TokenCName, Alignment))\r
626bece4
LG
1533 if PcdValue not in SkuValueMap:\r
1534 SkuValueMap[PcdValue] = []\r
ccaa7754 1535 VpdFile.Add(DscPcdEntry, SkuName, Sku.VpdOffset)\r
626bece4 1536 SkuValueMap[PcdValue].append(Sku)\r
e8a47801 1537 if not NeedProcessVpdMapFile and Sku.VpdOffset == "*":\r
f7496d71 1538 NeedProcessVpdMapFile = True\r
656d2539 1539 if DscPcdEntry.DatumType == TAB_VOID and PcdValue.startswith("L"):\r
0b6c5954 1540 UnicodePcdArray.add(DscPcdEntry)\r
e8a47801 1541 elif len(Sku.VariableName) > 0:\r
0b6c5954 1542 HiiPcdArray.add(DscPcdEntry)\r
e8a47801 1543 else:\r
0b6c5954
LG
1544 OtherPcdArray.add(DscPcdEntry)\r
1545\r
e8a47801 1546 # if the offset of a VPD is *, then it need to be fixed up by third party tool.\r
626bece4 1547 VpdSkuMap[DscPcd] = SkuValueMap\r
4231a819 1548 if (self.Platform.FlashDefinition is None or self.Platform.FlashDefinition == '') and \\r
e56468c0 1549 VpdFile.GetCount() != 0:\r
f7496d71 1550 EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE,\r
e56468c0 1551 "Fail to get FLASH_DEFINITION definition in DSC file %s which is required when DSC contains VPD PCD." % str(self.Platform.MetaFile))\r
47fea6af 1552\r
e56468c0 1553 if VpdFile.GetCount() != 0:\r
47854fd5
LG
1554\r
1555 self.FixVpdOffset(VpdFile)\r
1556\r
1557 self.FixVpdOffset(self.UpdateNVStoreMaxSize(VpdFile))\r
47fea6af 1558\r
e56468c0 1559 # Process VPD map file generated by third party BPDG tool\r
1560 if NeedProcessVpdMapFile:\r
91fa33ee 1561 VpdMapFilePath = os.path.join(self.BuildDir, TAB_FV_DIRECTORY, "%s.map" % self.Platform.VpdToolGuid)\r
e56468c0 1562 if os.path.exists(VpdMapFilePath):\r
1563 VpdFile.Read(VpdMapFilePath)\r
47fea6af 1564\r
e56468c0 1565 # Fixup "*" offset\r
626bece4
LG
1566 for pcd in VpdSkuMap:\r
1567 vpdinfo = VpdFile.GetVpdInfo(pcd)\r
1568 if vpdinfo is None:\r
e56468c0 1569 # just pick the a value to determine whether is unicode string type\r
626bece4
LG
1570 continue\r
1571 for pcdvalue in VpdSkuMap[pcd]:\r
1572 for sku in VpdSkuMap[pcd][pcdvalue]:\r
1573 for item in vpdinfo:\r
1574 if item[2] == pcdvalue:\r
1575 sku.VpdOffset = item[1]\r
e56468c0 1576 else:\r
1577 EdkLogger.error("build", FILE_READ_FAILURE, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath)\r
47fea6af 1578\r
626bece4
LG
1579 # Delete the DynamicPcdList At the last time enter into this function\r
1580 for Pcd in self._DynamicPcdList:\r
1581 # just pick the a value to determine whether is unicode string type\r
9eb87141 1582 Sku = Pcd.SkuInfoList.values()[0]\r
626bece4
LG
1583 Sku.VpdOffset = Sku.VpdOffset.strip()\r
1584\r
1585 if Pcd.DatumType not in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64, TAB_VOID, "BOOLEAN"]:\r
656d2539 1586 Pcd.DatumType = TAB_VOID\r
626bece4
LG
1587\r
1588 PcdValue = Sku.DefaultValue\r
656d2539 1589 if Pcd.DatumType == TAB_VOID and PcdValue.startswith("L"):\r
626bece4 1590 # if found PCD which datum value is unicode string the insert to left size of UnicodeIndex\r
0b6c5954 1591 UnicodePcdArray.add(Pcd)\r
626bece4
LG
1592 elif len(Sku.VariableName) > 0:\r
1593 # if found HII type PCD then insert to right of UnicodeIndex\r
0b6c5954 1594 HiiPcdArray.add(Pcd)\r
626bece4 1595 else:\r
0b6c5954 1596 OtherPcdArray.add(Pcd)\r
47fea6af 1597 del self._DynamicPcdList[:]\r
0b6c5954
LG
1598 self._DynamicPcdList.extend(list(UnicodePcdArray))\r
1599 self._DynamicPcdList.extend(list(HiiPcdArray))\r
1600 self._DynamicPcdList.extend(list(OtherPcdArray))\r
ccaa7754 1601 allskuset = [(SkuName, Sku.SkuId) for pcd in self._DynamicPcdList for (SkuName, Sku) in pcd.SkuInfoList.items()]\r
2b8a6c44
LG
1602 for pcd in self._DynamicPcdList:\r
1603 if len(pcd.SkuInfoList) == 1:\r
ccaa7754 1604 for (SkuName, SkuId) in allskuset:\r
86e6cf98 1605 if isinstance(SkuId, str) and eval(SkuId) == 0 or SkuId == 0:\r
2b8a6c44 1606 continue\r
55c84777 1607 pcd.SkuInfoList[SkuName] = copy.deepcopy(pcd.SkuInfoList[TAB_DEFAULT])\r
65eff519 1608 pcd.SkuInfoList[SkuName].SkuId = SkuId\r
71127ce8 1609 pcd.SkuInfoList[SkuName].SkuIdName = SkuName\r
a0a2cd1e 1610 self.AllPcdList = self._NonDynamicPcdList + self._DynamicPcdList\r
47854fd5 1611\r
ccaa7754 1612 def FixVpdOffset(self, VpdFile ):\r
91fa33ee 1613 FvPath = os.path.join(self.BuildDir, TAB_FV_DIRECTORY)\r
47854fd5
LG
1614 if not os.path.exists(FvPath):\r
1615 try:\r
1616 os.makedirs(FvPath)\r
1617 except:\r
1618 EdkLogger.error("build", FILE_WRITE_FAILURE, "Fail to create FV folder under %s" % self.BuildDir)\r
1619\r
1620 VpdFilePath = os.path.join(FvPath, "%s.txt" % self.Platform.VpdToolGuid)\r
1621\r
1622 if VpdFile.Write(VpdFilePath):\r
1623 # retrieve BPDG tool's path from tool_def.txt according to VPD_TOOL_GUID defined in DSC file.\r
1624 BPDGToolName = None\r
1625 for ToolDef in self.ToolDefinition.values():\r
27c4ceb4
GL
1626 if TAB_GUID in ToolDef and ToolDef[TAB_GUID] == self.Platform.VpdToolGuid:\r
1627 if "PATH" not in ToolDef:\r
47854fd5
LG
1628 EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "PATH attribute was not provided for BPDG guid tool %s in tools_def.txt" % self.Platform.VpdToolGuid)\r
1629 BPDGToolName = ToolDef["PATH"]\r
1630 break\r
1631 # Call third party GUID BPDG tool.\r
4231a819 1632 if BPDGToolName is not None:\r
47854fd5
LG
1633 VpdInfoFile.CallExtenalBPDGTool(BPDGToolName, VpdFilePath)\r
1634 else:\r
1635 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.")\r
1636\r
52302d4d 1637 ## Return the platform build data object\r
e6eae3b4
CJ
1638 @cached_property\r
1639 def Platform(self):\r
1640 return self.BuildDatabase[self.MetaFile, self.Arch, self.BuildTarget, self.ToolChain]\r
52302d4d
LG
1641\r
1642 ## Return platform name\r
e6eae3b4
CJ
1643 @cached_property\r
1644 def Name(self):\r
52302d4d
LG
1645 return self.Platform.PlatformName\r
1646\r
1647 ## Return the meta file GUID\r
e6eae3b4
CJ
1648 @cached_property\r
1649 def Guid(self):\r
52302d4d
LG
1650 return self.Platform.Guid\r
1651\r
1652 ## Return the platform version\r
e6eae3b4
CJ
1653 @cached_property\r
1654 def Version(self):\r
52302d4d
LG
1655 return self.Platform.Version\r
1656\r
1657 ## Return the FDF file name\r
e6eae3b4
CJ
1658 @cached_property\r
1659 def FdfFile(self):\r
1660 if self.Workspace.FdfFile:\r
1661 RetVal= mws.join(self.WorkspaceDir, self.Workspace.FdfFile)\r
1662 else:\r
1663 RetVal = ''\r
1664 return RetVal\r
52302d4d
LG
1665\r
1666 ## Return the build output directory platform specifies\r
e6eae3b4
CJ
1667 @cached_property\r
1668 def OutputDir(self):\r
52302d4d
LG
1669 return self.Platform.OutputDirectory\r
1670\r
1671 ## Return the directory to store all intermediate and final files built\r
e6eae3b4
CJ
1672 @cached_property\r
1673 def BuildDir(self):\r
1674 if os.path.isabs(self.OutputDir):\r
1675 GlobalData.gBuildDirectory = RetVal = path.join(\r
1676 path.abspath(self.OutputDir),\r
1677 self.BuildTarget + "_" + self.ToolChain,\r
1678 )\r
1679 else:\r
1680 GlobalData.gBuildDirectory = RetVal = path.join(\r
1681 self.WorkspaceDir,\r
1682 self.OutputDir,\r
1683 self.BuildTarget + "_" + self.ToolChain,\r
1684 )\r
1685 return RetVal\r
52302d4d
LG
1686\r
1687 ## Return directory of platform makefile\r
1688 #\r
1689 # @retval string Makefile directory\r
1690 #\r
e6eae3b4
CJ
1691 @cached_property\r
1692 def MakeFileDir(self):\r
1693 return path.join(self.BuildDir, self.Arch)\r
52302d4d
LG
1694\r
1695 ## Return build command string\r
1696 #\r
1697 # @retval string Build command string\r
1698 #\r
e6eae3b4
CJ
1699 @cached_property\r
1700 def BuildCommand(self):\r
1701 RetVal = []\r
1702 if "MAKE" in self.ToolDefinition and "PATH" in self.ToolDefinition["MAKE"]:\r
1703 RetVal += SplitOption(self.ToolDefinition["MAKE"]["PATH"])\r
1704 if "FLAGS" in self.ToolDefinition["MAKE"]:\r
1705 NewOption = self.ToolDefinition["MAKE"]["FLAGS"].strip()\r
1706 if NewOption != '':\r
1707 RetVal += SplitOption(NewOption)\r
1708 if "MAKE" in self.EdkIIBuildOption:\r
1709 if "FLAGS" in self.EdkIIBuildOption["MAKE"]:\r
1710 Flags = self.EdkIIBuildOption["MAKE"]["FLAGS"]\r
1711 if Flags.startswith('='):\r
1712 RetVal = [RetVal[0]] + [Flags[1:]]\r
1713 else:\r
1714 RetVal.append(Flags)\r
1715 return RetVal\r
52302d4d
LG
1716\r
1717 ## Get tool chain definition\r
1718 #\r
1719 # Get each tool defition for given tool chain from tools_def.txt and platform\r
1720 #\r
e6eae3b4
CJ
1721 @cached_property\r
1722 def ToolDefinition(self):\r
1723 ToolDefinition = self.Workspace.ToolDef.ToolsDefTxtDictionary\r
1724 if TAB_TOD_DEFINES_COMMAND_TYPE not in self.Workspace.ToolDef.ToolsDefTxtDatabase:\r
1725 EdkLogger.error('build', RESOURCE_NOT_AVAILABLE, "No tools found in configuration",\r
1726 ExtraData="[%s]" % self.MetaFile)\r
1727 RetVal = {}\r
1728 DllPathList = set()\r
1729 for Def in ToolDefinition:\r
1730 Target, Tag, Arch, Tool, Attr = Def.split("_")\r
1731 if Target != self.BuildTarget or Tag != self.ToolChain or Arch != self.Arch:\r
1732 continue\r
52302d4d 1733\r
e6eae3b4
CJ
1734 Value = ToolDefinition[Def]\r
1735 # don't record the DLL\r
1736 if Attr == "DLL":\r
1737 DllPathList.add(Value)\r
1738 continue\r
52302d4d 1739\r
e6eae3b4
CJ
1740 if Tool not in RetVal:\r
1741 RetVal[Tool] = {}\r
1742 RetVal[Tool][Attr] = Value\r
1743\r
1744 ToolsDef = ''\r
1745 if GlobalData.gOptions.SilentMode and "MAKE" in RetVal:\r
1746 if "FLAGS" not in RetVal["MAKE"]:\r
1747 RetVal["MAKE"]["FLAGS"] = ""\r
1748 RetVal["MAKE"]["FLAGS"] += " -s"\r
1749 MakeFlags = ''\r
1750 for Tool in RetVal:\r
1751 for Attr in RetVal[Tool]:\r
1752 Value = RetVal[Tool][Attr]\r
1753 if Tool in self._BuildOptionWithToolDef(RetVal) and Attr in self._BuildOptionWithToolDef(RetVal)[Tool]:\r
1754 # check if override is indicated\r
1755 if self._BuildOptionWithToolDef(RetVal)[Tool][Attr].startswith('='):\r
1756 Value = self._BuildOptionWithToolDef(RetVal)[Tool][Attr][1:]\r
1757 else:\r
1758 if Attr != 'PATH':\r
1759 Value += " " + self._BuildOptionWithToolDef(RetVal)[Tool][Attr]\r
52302d4d 1760 else:\r
e6eae3b4
CJ
1761 Value = self._BuildOptionWithToolDef(RetVal)[Tool][Attr]\r
1762\r
1763 if Attr == "PATH":\r
1764 # Don't put MAKE definition in the file\r
1765 if Tool != "MAKE":\r
1766 ToolsDef += "%s = %s\n" % (Tool, Value)\r
1767 elif Attr != "DLL":\r
1768 # Don't put MAKE definition in the file\r
1769 if Tool == "MAKE":\r
1770 if Attr == "FLAGS":\r
1771 MakeFlags = Value\r
1772 else:\r
1773 ToolsDef += "%s_%s = %s\n" % (Tool, Attr, Value)\r
1774 ToolsDef += "\n"\r
52302d4d 1775\r
e6eae3b4
CJ
1776 SaveFileOnChange(self.ToolDefinitionFile, ToolsDef)\r
1777 for DllPath in DllPathList:\r
1778 os.environ["PATH"] = DllPath + os.pathsep + os.environ["PATH"]\r
1779 os.environ["MAKE_FLAGS"] = MakeFlags\r
52302d4d 1780\r
e6eae3b4 1781 return RetVal\r
52302d4d
LG
1782\r
1783 ## Return the paths of tools\r
e6eae3b4
CJ
1784 @cached_property\r
1785 def ToolDefinitionFile(self):\r
1786 return os.path.join(self.MakeFileDir, "TOOLS_DEF." + self.Arch)\r
52302d4d
LG
1787\r
1788 ## Retrieve the toolchain family of given toolchain tag. Default to 'MSFT'.\r
e6eae3b4
CJ
1789 @cached_property\r
1790 def ToolChainFamily(self):\r
1791 ToolDefinition = self.Workspace.ToolDef.ToolsDefTxtDatabase\r
1792 if TAB_TOD_DEFINES_FAMILY not in ToolDefinition \\r
1793 or self.ToolChain not in ToolDefinition[TAB_TOD_DEFINES_FAMILY] \\r
1794 or not ToolDefinition[TAB_TOD_DEFINES_FAMILY][self.ToolChain]:\r
1795 EdkLogger.verbose("No tool chain family found in configuration for %s. Default to MSFT." \\r
1796 % self.ToolChain)\r
1797 RetVal = TAB_COMPILER_MSFT\r
1798 else:\r
1799 RetVal = ToolDefinition[TAB_TOD_DEFINES_FAMILY][self.ToolChain]\r
1800 return RetVal\r
1801\r
1802 @cached_property\r
1803 def BuildRuleFamily(self):\r
1804 ToolDefinition = self.Workspace.ToolDef.ToolsDefTxtDatabase\r
1805 if TAB_TOD_DEFINES_BUILDRULEFAMILY not in ToolDefinition \\r
1806 or self.ToolChain not in ToolDefinition[TAB_TOD_DEFINES_BUILDRULEFAMILY] \\r
1807 or not ToolDefinition[TAB_TOD_DEFINES_BUILDRULEFAMILY][self.ToolChain]:\r
1808 EdkLogger.verbose("No tool chain family found in configuration for %s. Default to MSFT." \\r
1809 % self.ToolChain)\r
1810 return TAB_COMPILER_MSFT\r
1811\r
1812 return ToolDefinition[TAB_TOD_DEFINES_BUILDRULEFAMILY][self.ToolChain]\r
52302d4d
LG
1813\r
1814 ## Return the build options specific for all modules in this platform\r
e6eae3b4
CJ
1815 @cached_property\r
1816 def BuildOption(self):\r
1817 return self._ExpandBuildOption(self.Platform.BuildOptions)\r
1818\r
1819 def _BuildOptionWithToolDef(self, ToolDef):\r
1820 return self._ExpandBuildOption(self.Platform.BuildOptions, ToolDef=ToolDef)\r
52302d4d
LG
1821\r
1822 ## Return the build options specific for EDK modules in this platform\r
e6eae3b4
CJ
1823 @cached_property\r
1824 def EdkBuildOption(self):\r
1825 return self._ExpandBuildOption(self.Platform.BuildOptions, EDK_NAME)\r
52302d4d
LG
1826\r
1827 ## Return the build options specific for EDKII modules in this platform\r
e6eae3b4
CJ
1828 @cached_property\r
1829 def EdkIIBuildOption(self):\r
1830 return self._ExpandBuildOption(self.Platform.BuildOptions, EDKII_NAME)\r
52302d4d 1831\r
97fa0ee9 1832 ## Parse build_rule.txt in Conf Directory.\r
52302d4d
LG
1833 #\r
1834 # @retval BuildRule object\r
1835 #\r
e6eae3b4
CJ
1836 @cached_property\r
1837 def BuildRule(self):\r
1838 BuildRuleFile = None\r
1839 if TAB_TAT_DEFINES_BUILD_RULE_CONF in self.Workspace.TargetTxt.TargetTxtDictionary:\r
1840 BuildRuleFile = self.Workspace.TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_BUILD_RULE_CONF]\r
1841 if not BuildRuleFile:\r
1842 BuildRuleFile = gDefaultBuildRuleFile\r
1843 RetVal = BuildRule(BuildRuleFile)\r
1844 if RetVal._FileVersion == "":\r
1845 RetVal._FileVersion = AutoGenReqBuildRuleVerNum\r
1846 else:\r
1847 if RetVal._FileVersion < AutoGenReqBuildRuleVerNum :\r
1848 # If Build Rule's version is less than the version number required by the tools, halting the build.\r
1849 EdkLogger.error("build", AUTOGEN_ERROR,\r
1850 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])"\\r
1851 % (RetVal._FileVersion, AutoGenReqBuildRuleVerNum))\r
1852 return RetVal\r
52302d4d
LG
1853\r
1854 ## Summarize the packages used by modules in this platform\r
e6eae3b4
CJ
1855 @cached_property\r
1856 def PackageList(self):\r
1857 RetVal = set()\r
1858 for La in self.LibraryAutoGenList:\r
1859 RetVal.update(La.DependentPackageList)\r
1860 for Ma in self.ModuleAutoGenList:\r
1861 RetVal.update(Ma.DependentPackageList)\r
1862 #Collect package set information from INF of FDF\r
1863 for ModuleFile in self._AsBuildModuleList:\r
1864 if ModuleFile in self.Platform.Modules:\r
1865 continue\r
1866 ModuleData = self.BuildDatabase[ModuleFile, self.Arch, self.BuildTarget, self.ToolChain]\r
1867 RetVal.update(ModuleData.Packages)\r
1868 return list(RetVal)\r
52302d4d 1869\r
e6eae3b4
CJ
1870 @cached_property\r
1871 def NonDynamicPcdDict(self):\r
1872 return {(Pcd.TokenCName, Pcd.TokenSpaceGuidCName):Pcd for Pcd in self.NonDynamicPcdList}\r
2bc3256c 1873\r
52302d4d 1874 ## Get list of non-dynamic PCDs\r
e6eae3b4
CJ
1875 @cached_property\r
1876 def NonDynamicPcdList(self):\r
1877 self.CollectPlatformDynamicPcds()\r
52302d4d
LG
1878 return self._NonDynamicPcdList\r
1879\r
1880 ## Get list of dynamic PCDs\r
e6eae3b4
CJ
1881 @cached_property\r
1882 def DynamicPcdList(self):\r
1883 self.CollectPlatformDynamicPcds()\r
52302d4d
LG
1884 return self._DynamicPcdList\r
1885\r
1886 ## Generate Token Number for all PCD\r
e6eae3b4
CJ
1887 @cached_property\r
1888 def PcdTokenNumber(self):\r
1889 RetVal = OrderedDict()\r
1890 TokenNumber = 1\r
1891 #\r
1892 # Make the Dynamic and DynamicEx PCD use within different TokenNumber area.\r
1893 # Such as:\r
1894 #\r
1895 # Dynamic PCD:\r
1896 # TokenNumber 0 ~ 10\r
1897 # DynamicEx PCD:\r
1898 # TokeNumber 11 ~ 20\r
1899 #\r
1900 for Pcd in self.DynamicPcdList:\r
1901 if Pcd.Phase == "PEI" and Pcd.Type in PCD_DYNAMIC_TYPE_SET:\r
1902 EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))\r
1903 RetVal[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
1904 TokenNumber += 1\r
1905\r
1906 for Pcd in self.DynamicPcdList:\r
1907 if Pcd.Phase == "PEI" and Pcd.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
1908 EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))\r
1909 RetVal[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
1910 TokenNumber += 1\r
1911\r
1912 for Pcd in self.DynamicPcdList:\r
1913 if Pcd.Phase == "DXE" and Pcd.Type in PCD_DYNAMIC_TYPE_SET:\r
1914 EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))\r
1915 RetVal[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
1916 TokenNumber += 1\r
1917\r
1918 for Pcd in self.DynamicPcdList:\r
1919 if Pcd.Phase == "DXE" and Pcd.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
1920 EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))\r
1921 RetVal[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
52302d4d 1922 TokenNumber += 1\r
52302d4d 1923\r
e6eae3b4
CJ
1924 for Pcd in self.NonDynamicPcdList:\r
1925 RetVal[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber\r
1926 TokenNumber += 1\r
1927 return RetVal\r
1928\r
4def57d9
CJ
1929 @cached_property\r
1930 def _MaList(self):\r
1931 for ModuleFile in self.Platform.Modules:\r
1932 Ma = ModuleAutoGen(\r
1933 self.Workspace,\r
1934 ModuleFile,\r
1935 self.BuildTarget,\r
1936 self.ToolChain,\r
1937 self.Arch,\r
1938 self.MetaFile\r
1939 )\r
1940 self.Platform.Modules[ModuleFile].M = Ma\r
1941 return [x.M for x in self.Platform.Modules.values()]\r
1942\r
e6eae3b4
CJ
1943 ## Summarize ModuleAutoGen objects of all modules to be built for this platform\r
1944 @cached_property\r
1945 def ModuleAutoGenList(self):\r
1946 RetVal = []\r
4def57d9 1947 for Ma in self._MaList:\r
e6eae3b4
CJ
1948 if Ma not in RetVal:\r
1949 RetVal.append(Ma)\r
1950 return RetVal\r
1951\r
1952 ## Summarize ModuleAutoGen objects of all libraries to be built for this platform\r
1953 @cached_property\r
1954 def LibraryAutoGenList(self):\r
1955 RetVal = []\r
4def57d9 1956 for Ma in self._MaList:\r
52302d4d 1957 for La in Ma.LibraryAutoGenList:\r
e6eae3b4
CJ
1958 if La not in RetVal:\r
1959 RetVal.append(La)\r
b23414f6
JC
1960 if Ma not in La.ReferenceModules:\r
1961 La.ReferenceModules.append(Ma)\r
e6eae3b4 1962 return RetVal\r
52302d4d
LG
1963\r
1964 ## Test if a module is supported by the platform\r
1965 #\r
1966 # An error will be raised directly if the module or its arch is not supported\r
1967 # by the platform or current configuration\r
1968 #\r
1969 def ValidModule(self, Module):\r
a0a2cd1e
FB
1970 return Module in self.Platform.Modules or Module in self.Platform.LibraryInstances \\r
1971 or Module in self._AsBuildModuleList\r
52302d4d
LG
1972\r
1973 ## Resolve the library classes in a module to library instances\r
1974 #\r
1975 # This method will not only resolve library classes but also sort the library\r
1976 # instances according to the dependency-ship.\r
1977 #\r
1978 # @param Module The module from which the library classes will be resolved\r
1979 #\r
1980 # @retval library_list List of library instances sorted\r
1981 #\r
1982 def ApplyLibraryInstance(self, Module):\r
25193a33
YZ
1983 # Cover the case that the binary INF file is list in the FDF file but not DSC file, return empty list directly\r
1984 if str(Module) not in self.Platform.Modules:\r
1985 return []\r
1986\r
c14b5861
JC
1987 return GetModuleLibInstances(Module,\r
1988 self.Platform,\r
1989 self.BuildDatabase,\r
1990 self.Arch,\r
1991 self.BuildTarget,\r
1992 self.ToolChain,\r
1993 self.MetaFile,\r
1994 EdkLogger)\r
52302d4d
LG
1995\r
1996 ## Override PCD setting (type, value, ...)\r
1997 #\r
1998 # @param ToPcd The PCD to be overrided\r
1999 # @param FromPcd The PCD overrideing from\r
2000 #\r
a253d217 2001 def _OverridePcd(self, ToPcd, FromPcd, Module="", Msg="", Library=""):\r
52302d4d
LG
2002 #\r
2003 # in case there's PCDs coming from FDF file, which have no type given.\r
2004 # at this point, ToPcd.Type has the type found from dependent\r
2005 # package\r
2006 #\r
2a29017e
YZ
2007 TokenCName = ToPcd.TokenCName\r
2008 for PcdItem in GlobalData.MixedPcd:\r
2009 if (ToPcd.TokenCName, ToPcd.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:\r
2010 TokenCName = PcdItem[0]\r
2011 break\r
4231a819 2012 if FromPcd is not None:\r
c93356ad 2013 if ToPcd.Pending and FromPcd.Type:\r
52302d4d 2014 ToPcd.Type = FromPcd.Type\r
caf74495
JC
2015 elif ToPcd.Type and FromPcd.Type\\r
2016 and ToPcd.Type != FromPcd.Type and ToPcd.Type in FromPcd.Type:\r
6b1f2cf4 2017 if ToPcd.Type.strip() == TAB_PCDS_DYNAMIC_EX:\r
47fea6af 2018 ToPcd.Type = FromPcd.Type\r
c93356ad 2019 elif ToPcd.Type and FromPcd.Type \\r
52302d4d 2020 and ToPcd.Type != FromPcd.Type:\r
a253d217
YF
2021 if Library:\r
2022 Module = str(Module) + " 's library file (" + str(Library) + ")"\r
52302d4d 2023 EdkLogger.error("build", OPTION_CONFLICT, "Mismatched PCD type",\r
a253d217 2024 ExtraData="%s.%s is used as [%s] in module %s, but as [%s] in %s."\\r
2a29017e 2025 % (ToPcd.TokenSpaceGuidCName, TokenCName,\r
a253d217 2026 ToPcd.Type, Module, FromPcd.Type, Msg),\r
52302d4d
LG
2027 File=self.MetaFile)\r
2028\r
6be94743 2029 if FromPcd.MaxDatumSize:\r
52302d4d 2030 ToPcd.MaxDatumSize = FromPcd.MaxDatumSize\r
c33081c9 2031 ToPcd.MaxSizeUserSet = FromPcd.MaxDatumSize\r
6be94743 2032 if FromPcd.DefaultValue:\r
52302d4d 2033 ToPcd.DefaultValue = FromPcd.DefaultValue\r
6be94743 2034 if FromPcd.TokenValue:\r
52302d4d 2035 ToPcd.TokenValue = FromPcd.TokenValue\r
6be94743 2036 if FromPcd.DatumType:\r
52302d4d 2037 ToPcd.DatumType = FromPcd.DatumType\r
6be94743 2038 if FromPcd.SkuInfoList:\r
52302d4d 2039 ToPcd.SkuInfoList = FromPcd.SkuInfoList\r
ced86858
ZZ
2040 if FromPcd.UserDefinedDefaultStoresFlag:\r
2041 ToPcd.UserDefinedDefaultStoresFlag = FromPcd.UserDefinedDefaultStoresFlag\r
726c501c 2042 # Add Flexible PCD format parse\r
726c501c 2043 if ToPcd.DefaultValue:\r
726c501c 2044 try:\r
e6eae3b4 2045 ToPcd.DefaultValue = ValueExpressionEx(ToPcd.DefaultValue, ToPcd.DatumType, self.Workspace._GuidDict)(True)\r
5b0671c1 2046 except BadExpression as Value:\r
726c501c
YZ
2047 EdkLogger.error('Parser', FORMAT_INVALID, 'PCD [%s.%s] Value "%s", %s' %(ToPcd.TokenSpaceGuidCName, ToPcd.TokenCName, ToPcd.DefaultValue, Value),\r
2048 File=self.MetaFile)\r
52302d4d
LG
2049\r
2050 # check the validation of datum\r
2051 IsValid, Cause = CheckPcdDatum(ToPcd.DatumType, ToPcd.DefaultValue)\r
2052 if not IsValid:\r
2053 EdkLogger.error('build', FORMAT_INVALID, Cause, File=self.MetaFile,\r
2a29017e 2054 ExtraData="%s.%s" % (ToPcd.TokenSpaceGuidCName, TokenCName))\r
82a6a960
BF
2055 ToPcd.validateranges = FromPcd.validateranges\r
2056 ToPcd.validlists = FromPcd.validlists\r
2057 ToPcd.expressions = FromPcd.expressions\r
6a147d6d 2058 ToPcd.CustomAttribute = FromPcd.CustomAttribute\r
52302d4d 2059\r
c93356ad 2060 if FromPcd is not None and ToPcd.DatumType == TAB_VOID and not ToPcd.MaxDatumSize:\r
52302d4d 2061 EdkLogger.debug(EdkLogger.DEBUG_9, "No MaxDatumSize specified for PCD %s.%s" \\r
2a29017e 2062 % (ToPcd.TokenSpaceGuidCName, TokenCName))\r
52302d4d 2063 Value = ToPcd.DefaultValue\r
c93356ad 2064 if not Value:\r
e8a47801 2065 ToPcd.MaxDatumSize = '1'\r
52302d4d 2066 elif Value[0] == 'L':\r
e8a47801 2067 ToPcd.MaxDatumSize = str((len(Value) - 2) * 2)\r
52302d4d
LG
2068 elif Value[0] == '{':\r
2069 ToPcd.MaxDatumSize = str(len(Value.split(',')))\r
2070 else:\r
e8a47801 2071 ToPcd.MaxDatumSize = str(len(Value) - 1)\r
52302d4d
LG
2072\r
2073 # apply default SKU for dynamic PCDS if specified one is not available\r
eece4292 2074 if (ToPcd.Type in PCD_DYNAMIC_TYPE_SET or ToPcd.Type in PCD_DYNAMIC_EX_TYPE_SET) \\r
c93356ad 2075 and not ToPcd.SkuInfoList:\r
52302d4d
LG
2076 if self.Platform.SkuName in self.Platform.SkuIds:\r
2077 SkuName = self.Platform.SkuName\r
2078 else:\r
55c84777 2079 SkuName = TAB_DEFAULT\r
52302d4d 2080 ToPcd.SkuInfoList = {\r
8518bf0b 2081 SkuName : SkuInfoClass(SkuName, self.Platform.SkuIds[SkuName][0], '', '', '', '', '', ToPcd.DefaultValue)\r
52302d4d
LG
2082 }\r
2083\r
2084 ## Apply PCD setting defined platform to a module\r
2085 #\r
2086 # @param Module The module from which the PCD setting will be overrided\r
2087 #\r
2088 # @retval PCD_list The list PCDs with settings from platform\r
2089 #\r
a253d217 2090 def ApplyPcdSetting(self, Module, Pcds, Library=""):\r
52302d4d 2091 # for each PCD in module\r
47fea6af
YZ
2092 for Name, Guid in Pcds:\r
2093 PcdInModule = Pcds[Name, Guid]\r
52302d4d 2094 # find out the PCD setting in platform\r
47fea6af
YZ
2095 if (Name, Guid) in self.Platform.Pcds:\r
2096 PcdInPlatform = self.Platform.Pcds[Name, Guid]\r
52302d4d
LG
2097 else:\r
2098 PcdInPlatform = None\r
2099 # then override the settings if any\r
a253d217 2100 self._OverridePcd(PcdInModule, PcdInPlatform, Module, Msg="DSC PCD sections", Library=Library)\r
52302d4d
LG
2101 # resolve the VariableGuid value\r
2102 for SkuId in PcdInModule.SkuInfoList:\r
2103 Sku = PcdInModule.SkuInfoList[SkuId]\r
2104 if Sku.VariableGuid == '': continue\r
c28d2e10 2105 Sku.VariableGuidValue = GuidValue(Sku.VariableGuid, self.PackageList, self.MetaFile.Path)\r
4231a819 2106 if Sku.VariableGuidValue is None:\r
8252e6bf 2107 PackageList = "\n\t".join(str(P) for P in self.PackageList)\r
52302d4d
LG
2108 EdkLogger.error(\r
2109 'build',\r
2110 RESOURCE_NOT_AVAILABLE,\r
2111 "Value of GUID [%s] is not found in" % Sku.VariableGuid,\r
2112 ExtraData=PackageList + "\n\t(used with %s.%s from module %s)" \\r
2113 % (Guid, Name, str(Module)),\r
2114 File=self.MetaFile\r
2115 )\r
2116\r
2117 # override PCD settings with module specific setting\r
2118 if Module in self.Platform.Modules:\r
2119 PlatformModule = self.Platform.Modules[str(Module)]\r
2120 for Key in PlatformModule.Pcds:\r
aa9aa47e 2121 Flag = False\r
52302d4d 2122 if Key in Pcds:\r
aa9aa47e
YZ
2123 ToPcd = Pcds[Key]\r
2124 Flag = True\r
2125 elif Key in GlobalData.MixedPcd:\r
2126 for PcdItem in GlobalData.MixedPcd[Key]:\r
2127 if PcdItem in Pcds:\r
2128 ToPcd = Pcds[PcdItem]\r
2129 Flag = True\r
2130 break\r
2131 if Flag:\r
a253d217 2132 self._OverridePcd(ToPcd, PlatformModule.Pcds[Key], Module, Msg="DSC Components Module scoped PCD section", Library=Library)\r
cdbf45ad
YZ
2133 # use PCD value to calculate the MaxDatumSize when it is not specified\r
2134 for Name, Guid in Pcds:\r
2135 Pcd = Pcds[Name, Guid]\r
c93356ad 2136 if Pcd.DatumType == TAB_VOID and not Pcd.MaxDatumSize:\r
c33081c9 2137 Pcd.MaxSizeUserSet = None\r
cdbf45ad 2138 Value = Pcd.DefaultValue\r
c93356ad 2139 if not Value:\r
cdbf45ad
YZ
2140 Pcd.MaxDatumSize = '1'\r
2141 elif Value[0] == 'L':\r
2142 Pcd.MaxDatumSize = str((len(Value) - 2) * 2)\r
2143 elif Value[0] == '{':\r
2144 Pcd.MaxDatumSize = str(len(Value.split(',')))\r
2145 else:\r
2146 Pcd.MaxDatumSize = str(len(Value) - 1)\r
52302d4d
LG
2147 return Pcds.values()\r
2148\r
2149 ## Resolve library names to library modules\r
2150 #\r
b36d134f 2151 # (for Edk.x modules)\r
52302d4d
LG
2152 #\r
2153 # @param Module The module from which the library names will be resolved\r
2154 #\r
2155 # @retval library_list The list of library modules\r
2156 #\r
2157 def ResolveLibraryReference(self, Module):\r
2158 EdkLogger.verbose("")\r
2159 EdkLogger.verbose("Library instances of module [%s] [%s]:" % (str(Module), self.Arch))\r
2160 LibraryConsumerList = [Module]\r
2161\r
b36d134f 2162 # "CompilerStub" is a must for Edk modules\r
52302d4d
LG
2163 if Module.Libraries:\r
2164 Module.Libraries.append("CompilerStub")\r
2165 LibraryList = []\r
2166 while len(LibraryConsumerList) > 0:\r
2167 M = LibraryConsumerList.pop()\r
2168 for LibraryName in M.Libraries:\r
2169 Library = self.Platform.LibraryClasses[LibraryName, ':dummy:']\r
4231a819 2170 if Library is None:\r
9eb87141 2171 for Key in self.Platform.LibraryClasses.data:\r
52302d4d
LG
2172 if LibraryName.upper() == Key.upper():\r
2173 Library = self.Platform.LibraryClasses[Key, ':dummy:']\r
2174 break\r
4231a819 2175 if Library is None:\r
52302d4d
LG
2176 EdkLogger.warn("build", "Library [%s] is not found" % LibraryName, File=str(M),\r
2177 ExtraData="\t%s [%s]" % (str(Module), self.Arch))\r
2178 continue\r
2179\r
2180 if Library not in LibraryList:\r
2181 LibraryList.append(Library)\r
2182 LibraryConsumerList.append(Library)\r
2183 EdkLogger.verbose("\t" + LibraryName + " : " + str(Library) + ' ' + str(type(Library)))\r
2184 return LibraryList\r
2185\r
6780eef1
LG
2186 ## Calculate the priority value of the build option\r
2187 #\r
2188 # @param Key Build option definition contain: TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE\r
2189 #\r
2190 # @retval Value Priority value based on the priority list.\r
2191 #\r
2192 def CalculatePriorityValue(self, Key):\r
47fea6af
YZ
2193 Target, ToolChain, Arch, CommandType, Attr = Key.split('_')\r
2194 PriorityValue = 0x11111\r
6780eef1
LG
2195 if Target == "*":\r
2196 PriorityValue &= 0x01111\r
2197 if ToolChain == "*":\r
2198 PriorityValue &= 0x10111\r
2199 if Arch == "*":\r
2200 PriorityValue &= 0x11011\r
2201 if CommandType == "*":\r
2202 PriorityValue &= 0x11101\r
2203 if Attr == "*":\r
2204 PriorityValue &= 0x11110\r
47fea6af
YZ
2205\r
2206 return self.PrioList["0x%0.5x" % PriorityValue]\r
2207\r
6780eef1 2208\r
52302d4d
LG
2209 ## Expand * in build option key\r
2210 #\r
2211 # @param Options Options to be expanded\r
e6eae3b4
CJ
2212 # @param ToolDef Use specified ToolDef instead of full version.\r
2213 # This is needed during initialization to prevent\r
2214 # infinite recursion betweeh BuildOptions,\r
2215 # ToolDefinition, and this function.\r
52302d4d
LG
2216 #\r
2217 # @retval options Options expanded\r
f7496d71 2218 #\r
e6eae3b4
CJ
2219 def _ExpandBuildOption(self, Options, ModuleStyle=None, ToolDef=None):\r
2220 if not ToolDef:\r
2221 ToolDef = self.ToolDefinition\r
52302d4d
LG
2222 BuildOptions = {}\r
2223 FamilyMatch = False\r
2224 FamilyIsNull = True\r
47fea6af 2225\r
6780eef1
LG
2226 OverrideList = {}\r
2227 #\r
2228 # Construct a list contain the build options which need override.\r
2229 #\r
2230 for Key in Options:\r
2231 #\r
2232 # Key[0] -- tool family\r
2233 # Key[1] -- TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE\r
2234 #\r
1ba5124e 2235 if (Key[0] == self.BuildRuleFamily and\r
4231a819 2236 (ModuleStyle is None or len(Key) < 3 or (len(Key) > 2 and Key[2] == ModuleStyle))):\r
6780eef1 2237 Target, ToolChain, Arch, CommandType, Attr = Key[1].split('_')\r
caf74495
JC
2238 if (Target == self.BuildTarget or Target == "*") and\\r
2239 (ToolChain == self.ToolChain or ToolChain == "*") and\\r
2240 (Arch == self.Arch or Arch == "*") and\\r
2241 Options[Key].startswith("="):\r
2242\r
2243 if OverrideList.get(Key[1]) is not None:\r
2244 OverrideList.pop(Key[1])\r
2245 OverrideList[Key[1]] = Options[Key]\r
f7496d71 2246\r
6780eef1 2247 #\r
f7496d71 2248 # Use the highest priority value.\r
6780eef1
LG
2249 #\r
2250 if (len(OverrideList) >= 2):\r
47fea6af 2251 KeyList = OverrideList.keys()\r
6780eef1 2252 for Index in range(len(KeyList)):\r
47fea6af 2253 NowKey = KeyList[Index]\r
6780eef1
LG
2254 Target1, ToolChain1, Arch1, CommandType1, Attr1 = NowKey.split("_")\r
2255 for Index1 in range(len(KeyList) - Index - 1):\r
2256 NextKey = KeyList[Index1 + Index + 1]\r
2257 #\r
2258 # Compare two Key, if one is included by another, choose the higher priority one\r
f7496d71 2259 #\r
6780eef1 2260 Target2, ToolChain2, Arch2, CommandType2, Attr2 = NextKey.split("_")\r
caf74495
JC
2261 if (Target1 == Target2 or Target1 == "*" or Target2 == "*") and\\r
2262 (ToolChain1 == ToolChain2 or ToolChain1 == "*" or ToolChain2 == "*") and\\r
2263 (Arch1 == Arch2 or Arch1 == "*" or Arch2 == "*") and\\r
2264 (CommandType1 == CommandType2 or CommandType1 == "*" or CommandType2 == "*") and\\r
2265 (Attr1 == Attr2 or Attr1 == "*" or Attr2 == "*"):\r
2266\r
2267 if self.CalculatePriorityValue(NowKey) > self.CalculatePriorityValue(NextKey):\r
2268 if Options.get((self.BuildRuleFamily, NextKey)) is not None:\r
2269 Options.pop((self.BuildRuleFamily, NextKey))\r
2270 else:\r
2271 if Options.get((self.BuildRuleFamily, NowKey)) is not None:\r
2272 Options.pop((self.BuildRuleFamily, NowKey))\r
f7496d71 2273\r
52302d4d 2274 for Key in Options:\r
4231a819 2275 if ModuleStyle is not None and len (Key) > 2:\r
52302d4d
LG
2276 # Check Module style is EDK or EDKII.\r
2277 # Only append build option for the matched style module.\r
2278 if ModuleStyle == EDK_NAME and Key[2] != EDK_NAME:\r
2279 continue\r
2280 elif ModuleStyle == EDKII_NAME and Key[2] != EDKII_NAME:\r
2281 continue\r
2282 Family = Key[0]\r
2283 Target, Tag, Arch, Tool, Attr = Key[1].split("_")\r
2284 # if tool chain family doesn't match, skip it\r
e6eae3b4 2285 if Tool in ToolDef and Family != "":\r
52302d4d 2286 FamilyIsNull = False\r
e6eae3b4
CJ
2287 if ToolDef[Tool].get(TAB_TOD_DEFINES_BUILDRULEFAMILY, "") != "":\r
2288 if Family != ToolDef[Tool][TAB_TOD_DEFINES_BUILDRULEFAMILY]:\r
52302d4d 2289 continue\r
e6eae3b4 2290 elif Family != ToolDef[Tool][TAB_TOD_DEFINES_FAMILY]:\r
52302d4d
LG
2291 continue\r
2292 FamilyMatch = True\r
2293 # expand any wildcard\r
2294 if Target == "*" or Target == self.BuildTarget:\r
2295 if Tag == "*" or Tag == self.ToolChain:\r
2296 if Arch == "*" or Arch == self.Arch:\r
2297 if Tool not in BuildOptions:\r
2298 BuildOptions[Tool] = {}\r
5015bee2 2299 if Attr != "FLAGS" or Attr not in BuildOptions[Tool] or Options[Key].startswith('='):\r
52302d4d
LG
2300 BuildOptions[Tool][Attr] = Options[Key]\r
2301 else:\r
95816356
YZ
2302 # append options for the same tool except PATH\r
2303 if Attr != 'PATH':\r
2304 BuildOptions[Tool][Attr] += " " + Options[Key]\r
2305 else:\r
2306 BuildOptions[Tool][Attr] = Options[Key]\r
52302d4d
LG
2307 # Build Option Family has been checked, which need't to be checked again for family.\r
2308 if FamilyMatch or FamilyIsNull:\r
2309 return BuildOptions\r
1ba5124e 2310\r
52302d4d 2311 for Key in Options:\r
4231a819 2312 if ModuleStyle is not None and len (Key) > 2:\r
52302d4d
LG
2313 # Check Module style is EDK or EDKII.\r
2314 # Only append build option for the matched style module.\r
2315 if ModuleStyle == EDK_NAME and Key[2] != EDK_NAME:\r
2316 continue\r
2317 elif ModuleStyle == EDKII_NAME and Key[2] != EDKII_NAME:\r
2318 continue\r
2319 Family = Key[0]\r
2320 Target, Tag, Arch, Tool, Attr = Key[1].split("_")\r
2321 # if tool chain family doesn't match, skip it\r
e6eae3b4 2322 if Tool not in ToolDef or Family == "":\r
52302d4d
LG
2323 continue\r
2324 # option has been added before\r
e6eae3b4 2325 if Family != ToolDef[Tool][TAB_TOD_DEFINES_FAMILY]:\r
52302d4d
LG
2326 continue\r
2327\r
2328 # expand any wildcard\r
2329 if Target == "*" or Target == self.BuildTarget:\r
2330 if Tag == "*" or Tag == self.ToolChain:\r
2331 if Arch == "*" or Arch == self.Arch:\r
2332 if Tool not in BuildOptions:\r
2333 BuildOptions[Tool] = {}\r
5015bee2 2334 if Attr != "FLAGS" or Attr not in BuildOptions[Tool] or Options[Key].startswith('='):\r
52302d4d
LG
2335 BuildOptions[Tool][Attr] = Options[Key]\r
2336 else:\r
95816356
YZ
2337 # append options for the same tool except PATH\r
2338 if Attr != 'PATH':\r
2339 BuildOptions[Tool][Attr] += " " + Options[Key]\r
2340 else:\r
2341 BuildOptions[Tool][Attr] = Options[Key]\r
52302d4d
LG
2342 return BuildOptions\r
2343\r
2344 ## Append build options in platform to a module\r
2345 #\r
2346 # @param Module The module to which the build options will be appened\r
2347 #\r
2348 # @retval options The options appended with build options in platform\r
2349 #\r
2350 def ApplyBuildOption(self, Module):\r
2351 # Get the different options for the different style module\r
2352 if Module.AutoGenVersion < 0x00010005:\r
2353 PlatformOptions = self.EdkBuildOption\r
35f69db9 2354 ModuleTypeOptions = self.Platform.GetBuildOptionsByModuleType(EDK_NAME, Module.ModuleType)\r
52302d4d
LG
2355 else:\r
2356 PlatformOptions = self.EdkIIBuildOption\r
35f69db9
YL
2357 ModuleTypeOptions = self.Platform.GetBuildOptionsByModuleType(EDKII_NAME, Module.ModuleType)\r
2358 ModuleTypeOptions = self._ExpandBuildOption(ModuleTypeOptions)\r
52302d4d
LG
2359 ModuleOptions = self._ExpandBuildOption(Module.BuildOptions)\r
2360 if Module in self.Platform.Modules:\r
2361 PlatformModule = self.Platform.Modules[str(Module)]\r
2362 PlatformModuleOptions = self._ExpandBuildOption(PlatformModule.BuildOptions)\r
2363 else:\r
2364 PlatformModuleOptions = {}\r
2365\r
fe4bf2f9 2366 BuildRuleOrder = None\r
35f69db9 2367 for Options in [self.ToolDefinition, ModuleOptions, PlatformOptions, ModuleTypeOptions, PlatformModuleOptions]:\r
fe4bf2f9
YL
2368 for Tool in Options:\r
2369 for Attr in Options[Tool]:\r
2370 if Attr == TAB_TOD_DEFINES_BUILDRULEORDER:\r
2371 BuildRuleOrder = Options[Tool][Attr]\r
2372\r
35f69db9
YL
2373 AllTools = set(ModuleOptions.keys() + PlatformOptions.keys() +\r
2374 PlatformModuleOptions.keys() + ModuleTypeOptions.keys() +\r
2375 self.ToolDefinition.keys())\r
339fe8dd 2376 BuildOptions = defaultdict(lambda: defaultdict(str))\r
52302d4d 2377 for Tool in AllTools:\r
35f69db9 2378 for Options in [self.ToolDefinition, ModuleOptions, PlatformOptions, ModuleTypeOptions, PlatformModuleOptions]:\r
52302d4d
LG
2379 if Tool not in Options:\r
2380 continue\r
2381 for Attr in Options[Tool]:\r
fe4bf2f9
YL
2382 #\r
2383 # Do not generate it in Makefile\r
2384 #\r
2385 if Attr == TAB_TOD_DEFINES_BUILDRULEORDER:\r
2386 continue\r
339fe8dd 2387 Value = Options[Tool][Attr]\r
52302d4d
LG
2388 # check if override is indicated\r
2389 if Value.startswith('='):\r
339fe8dd 2390 BuildOptions[Tool][Attr] = mws.handleWsMacro(Value[1:])\r
5015bee2 2391 else:\r
95816356 2392 if Attr != 'PATH':\r
339fe8dd 2393 BuildOptions[Tool][Attr] += " " + mws.handleWsMacro(Value)\r
95816356 2394 else:\r
339fe8dd
CJ
2395 BuildOptions[Tool][Attr] = mws.handleWsMacro(Value)\r
2396\r
4231a819 2397 if Module.AutoGenVersion < 0x00010005 and self.Workspace.UniFlag is not None:\r
f3decdc3
LG
2398 #\r
2399 # Override UNI flag only for EDK module.\r
2400 #\r
f3decdc3 2401 BuildOptions['BUILD']['FLAGS'] = self.Workspace.UniFlag\r
fe4bf2f9 2402 return BuildOptions, BuildRuleOrder\r
52302d4d 2403\r
caf74495
JC
2404#\r
2405# extend lists contained in a dictionary with lists stored in another dictionary\r
2406# if CopyToDict is not derived from DefaultDict(list) then this may raise exception\r
2407#\r
2408def ExtendCopyDictionaryLists(CopyToDict, CopyFromDict):\r
2409 for Key in CopyFromDict:\r
2410 CopyToDict[Key].extend(CopyFromDict[Key])\r
2411\r
b23414f6
JC
2412# Create a directory specified by a set of path elements and return the full path\r
2413def _MakeDir(PathList):\r
2414 RetVal = path.join(*PathList)\r
2415 CreateDirectory(RetVal)\r
2416 return RetVal\r
caf74495 2417\r
52302d4d
LG
2418## ModuleAutoGen class\r
2419#\r
2420# This class encapsules the AutoGen behaviors for the build tools. In addition to\r
2421# the generation of AutoGen.h and AutoGen.c, it will generate *.depex file according\r
2422# to the [depex] section in module's inf file.\r
2423#\r
2424class ModuleAutoGen(AutoGen):\r
b24e99f7
CJ
2425 # call super().__init__ then call the worker function with different parameter count\r
2426 def __init__(self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):\r
b23414f6 2427 if not hasattr(self, "_Init"):\r
4ce4f757 2428 super().__init__(Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)\r
b24e99f7
CJ
2429 self._InitWorker(Workspace, MetaFile, Target, Toolchain, Arch, *args)\r
2430 self._Init = True\r
2431\r
b23414f6 2432 ## Cache the timestamps of metafiles of every module in a class attribute\r
c17956e0
DL
2433 #\r
2434 TimeDict = {}\r
2435\r
b24e99f7 2436 def __new__(cls, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):\r
b24e99f7
CJ
2437 # check if this module is employed by active platform\r
2438 if not PlatformAutoGen(Workspace, args[0], Target, Toolchain, Arch).ValidModule(MetaFile):\r
2439 EdkLogger.verbose("Module [%s] for [%s] is not employed by active platform\n" \\r
2440 % (MetaFile, Arch))\r
2441 return None\r
4ce4f757 2442 return super().__new__(cls, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)\r
f7496d71 2443\r
b24e99f7 2444 ## Initialize ModuleAutoGen\r
52302d4d
LG
2445 #\r
2446 # @param Workspace EdkIIWorkspaceBuild object\r
2447 # @param ModuleFile The path of module file\r
2448 # @param Target Build target (DEBUG, RELEASE)\r
2449 # @param Toolchain Name of tool chain\r
2450 # @param Arch The arch the module supports\r
2451 # @param PlatformFile Platform meta-file\r
2452 #\r
b24e99f7 2453 def _InitWorker(self, Workspace, ModuleFile, Target, Toolchain, Arch, PlatformFile):\r
52302d4d
LG
2454 EdkLogger.debug(EdkLogger.DEBUG_9, "AutoGen module [%s] [%s]" % (ModuleFile, Arch))\r
2455 GlobalData.gProcessingFile = "%s [%s, %s, %s]" % (ModuleFile, Arch, Toolchain, Target)\r
2456\r
2457 self.Workspace = Workspace\r
2458 self.WorkspaceDir = Workspace.WorkspaceDir\r
52302d4d
LG
2459 self.MetaFile = ModuleFile\r
2460 self.PlatformInfo = PlatformAutoGen(Workspace, PlatformFile, Target, Toolchain, Arch)\r
52302d4d
LG
2461\r
2462 self.SourceDir = self.MetaFile.SubDir\r
05cc51ad 2463 self.SourceDir = mws.relpath(self.SourceDir, self.WorkspaceDir)\r
97fa0ee9 2464\r
52302d4d
LG
2465 self.SourceOverrideDir = None\r
2466 # use overrided path defined in DSC file\r
2467 if self.MetaFile.Key in GlobalData.gOverrideDir:\r
2468 self.SourceOverrideDir = GlobalData.gOverrideDir[self.MetaFile.Key]\r
2469\r
2470 self.ToolChain = Toolchain\r
2471 self.BuildTarget = Target\r
2472 self.Arch = Arch\r
2473 self.ToolChainFamily = self.PlatformInfo.ToolChainFamily\r
2474 self.BuildRuleFamily = self.PlatformInfo.BuildRuleFamily\r
2475\r
52302d4d 2476 self.IsCodeFileCreated = False\r
da92f276
LG
2477 self.IsAsBuiltInfCreated = False\r
2478 self.DepexGenerated = False\r
52302d4d
LG
2479\r
2480 self.BuildDatabase = self.Workspace.BuildDatabase\r
fe4bf2f9 2481 self.BuildRuleOrder = None\r
1b8eca8b 2482 self.BuildTime = 0\r
52302d4d 2483\r
caf74495 2484 self._PcdComments = OrderedListDict()\r
caf74495 2485 self._GuidComments = OrderedListDict()\r
caf74495 2486 self._ProtocolComments = OrderedListDict()\r
caf74495 2487 self._PpiComments = OrderedListDict()\r
52302d4d
LG
2488 self._BuildTargets = None\r
2489 self._IntroBuildTargetList = None\r
2490 self._FinalBuildTargetList = None\r
2491 self._FileTypes = None\r
c17956e0
DL
2492\r
2493 self.AutoGenDepSet = set()\r
b23414f6 2494 self.ReferenceModules = []\r
2bc3256c 2495 self.ConstPcd = {}\r
52302d4d 2496\r
a10def91 2497\r
52302d4d
LG
2498 def __repr__(self):\r
2499 return "%s [%s]" % (self.MetaFile, self.Arch)\r
2500\r
2bc3256c 2501 # Get FixedAtBuild Pcds of this Module\r
b23414f6
JC
2502 @cached_property\r
2503 def FixedAtBuildPcds(self):\r
2504 RetVal = []\r
2bc3256c 2505 for Pcd in self.ModulePcdList:\r
6b1f2cf4 2506 if Pcd.Type != TAB_PCDS_FIXED_AT_BUILD:\r
2bc3256c 2507 continue\r
b23414f6
JC
2508 if Pcd not in RetVal:\r
2509 RetVal.append(Pcd)\r
2510 return RetVal\r
2511\r
2512 @cached_property\r
2513 def FixedVoidTypePcds(self):\r
2514 RetVal = {}\r
2515 for Pcd in self.FixedAtBuildPcds:\r
2516 if Pcd.DatumType == TAB_VOID:\r
2517 if '{}.{}'.format(Pcd.TokenSpaceGuidCName, Pcd.TokenCName) not in RetVal:\r
2518 RetVal['{}.{}'.format(Pcd.TokenSpaceGuidCName, Pcd.TokenCName)] = Pcd.DefaultValue\r
2519 return RetVal\r
2520\r
2521 @property\r
2522 def UniqueBaseName(self):\r
867d1cd4
YL
2523 BaseName = self.Name\r
2524 for Module in self.PlatformInfo.ModuleAutoGenList:\r
2525 if Module.MetaFile == self.MetaFile:\r
2526 continue\r
2527 if Module.Name == self.Name:\r
867d1cd4
YL
2528 if uuid.UUID(Module.Guid) == uuid.UUID(self.Guid):\r
2529 EdkLogger.error("build", FILE_DUPLICATED, 'Modules have same BaseName and FILE_GUID:\n'\r
2530 ' %s\n %s' % (Module.MetaFile, self.MetaFile))\r
2531 BaseName = '%s_%s' % (self.Name, self.Guid)\r
2532 return BaseName\r
2533\r
52302d4d 2534 # Macros could be used in build_rule.txt (also Makefile)\r
b23414f6
JC
2535 @cached_property\r
2536 def Macros(self):\r
2537 return OrderedDict((\r
2538 ("WORKSPACE" ,self.WorkspaceDir),\r
2539 ("MODULE_NAME" ,self.Name),\r
2540 ("MODULE_NAME_GUID" ,self.UniqueBaseName),\r
2541 ("MODULE_GUID" ,self.Guid),\r
2542 ("MODULE_VERSION" ,self.Version),\r
2543 ("MODULE_TYPE" ,self.ModuleType),\r
2544 ("MODULE_FILE" ,str(self.MetaFile)),\r
2545 ("MODULE_FILE_BASE_NAME" ,self.MetaFile.BaseName),\r
2546 ("MODULE_RELATIVE_DIR" ,self.SourceDir),\r
2547 ("MODULE_DIR" ,self.SourceDir),\r
2548 ("BASE_NAME" ,self.Name),\r
2549 ("ARCH" ,self.Arch),\r
2550 ("TOOLCHAIN" ,self.ToolChain),\r
2551 ("TOOLCHAIN_TAG" ,self.ToolChain),\r
2552 ("TOOL_CHAIN_TAG" ,self.ToolChain),\r
2553 ("TARGET" ,self.BuildTarget),\r
2554 ("BUILD_DIR" ,self.PlatformInfo.BuildDir),\r
2555 ("BIN_DIR" ,os.path.join(self.PlatformInfo.BuildDir, self.Arch)),\r
2556 ("LIB_DIR" ,os.path.join(self.PlatformInfo.BuildDir, self.Arch)),\r
2557 ("MODULE_BUILD_DIR" ,self.BuildDir),\r
2558 ("OUTPUT_DIR" ,self.OutputDir),\r
2559 ("DEBUG_DIR" ,self.DebugDir),\r
2560 ("DEST_DIR_OUTPUT" ,self.OutputDir),\r
2561 ("DEST_DIR_DEBUG" ,self.DebugDir),\r
2562 ("PLATFORM_NAME" ,self.PlatformInfo.Name),\r
2563 ("PLATFORM_GUID" ,self.PlatformInfo.Guid),\r
2564 ("PLATFORM_VERSION" ,self.PlatformInfo.Version),\r
2565 ("PLATFORM_RELATIVE_DIR" ,self.PlatformInfo.SourceDir),\r
2566 ("PLATFORM_DIR" ,mws.join(self.WorkspaceDir, self.PlatformInfo.SourceDir)),\r
2567 ("PLATFORM_OUTPUT_DIR" ,self.PlatformInfo.OutputDir),\r
2568 ("FFS_OUTPUT_DIR" ,self.FfsOutputDir)\r
2569 ))\r
52302d4d
LG
2570\r
2571 ## Return the module build data object\r
b23414f6
JC
2572 @cached_property\r
2573 def Module(self):\r
e6c62ab7 2574 return self.BuildDatabase[self.MetaFile, self.Arch, self.BuildTarget, self.ToolChain]\r
52302d4d
LG
2575\r
2576 ## Return the module name\r
b23414f6
JC
2577 @cached_property\r
2578 def Name(self):\r
52302d4d
LG
2579 return self.Module.BaseName\r
2580\r
b36d134f 2581 ## Return the module DxsFile if exist\r
b23414f6
JC
2582 @cached_property\r
2583 def DxsFile(self):\r
b36d134f
LG
2584 return self.Module.DxsFile\r
2585\r
52302d4d 2586 ## Return the module meta-file GUID\r
b23414f6
JC
2587 @cached_property\r
2588 def Guid(self):\r
97fa0ee9
YL
2589 #\r
2590 # To build same module more than once, the module path with FILE_GUID overridden has\r
2591 # the file name FILE_GUIDmodule.inf, but the relative path (self.MetaFile.File) is the realy path\r
2592 # in DSC. The overridden GUID can be retrieved from file name\r
2593 #\r
2594 if os.path.basename(self.MetaFile.File) != os.path.basename(self.MetaFile.Path):\r
2595 #\r
2596 # Length of GUID is 36\r
2597 #\r
2598 return os.path.basename(self.MetaFile.Path)[:36]\r
52302d4d
LG
2599 return self.Module.Guid\r
2600\r
2601 ## Return the module version\r
b23414f6
JC
2602 @cached_property\r
2603 def Version(self):\r
52302d4d
LG
2604 return self.Module.Version\r
2605\r
2606 ## Return the module type\r
b23414f6
JC
2607 @cached_property\r
2608 def ModuleType(self):\r
52302d4d
LG
2609 return self.Module.ModuleType\r
2610\r
b36d134f 2611 ## Return the component type (for Edk.x style of module)\r
b23414f6
JC
2612 @cached_property\r
2613 def ComponentType(self):\r
52302d4d
LG
2614 return self.Module.ComponentType\r
2615\r
2616 ## Return the build type\r
b23414f6
JC
2617 @cached_property\r
2618 def BuildType(self):\r
52302d4d
LG
2619 return self.Module.BuildType\r
2620\r
2621 ## Return the PCD_IS_DRIVER setting\r
b23414f6
JC
2622 @cached_property\r
2623 def PcdIsDriver(self):\r
52302d4d
LG
2624 return self.Module.PcdIsDriver\r
2625\r
2626 ## Return the autogen version, i.e. module meta-file version\r
b23414f6
JC
2627 @cached_property\r
2628 def AutoGenVersion(self):\r
52302d4d
LG
2629 return self.Module.AutoGenVersion\r
2630\r
2631 ## Check if the module is library or not\r
b23414f6
JC
2632 @cached_property\r
2633 def IsLibrary(self):\r
2634 return bool(self.Module.LibraryClass)\r
52302d4d 2635\r
e8a47801 2636 ## Check if the module is binary module or not\r
b23414f6
JC
2637 @cached_property\r
2638 def IsBinaryModule(self):\r
e8a47801
LG
2639 return self.Module.IsBinaryModule\r
2640\r
52302d4d 2641 ## Return the directory to store intermediate files of the module\r
b23414f6
JC
2642 @cached_property\r
2643 def BuildDir(self):\r
2644 return _MakeDir((\r
52302d4d
LG
2645 self.PlatformInfo.BuildDir,\r
2646 self.Arch,\r
2647 self.SourceDir,\r
2648 self.MetaFile.BaseName\r
b23414f6 2649 ))\r
52302d4d
LG
2650\r
2651 ## Return the directory to store the intermediate object files of the mdoule\r
b23414f6
JC
2652 @cached_property\r
2653 def OutputDir(self):\r
2654 return _MakeDir((self.BuildDir, "OUTPUT"))\r
2655\r
2656 ## Return the directory path to store ffs file\r
2657 @cached_property\r
2658 def FfsOutputDir(self):\r
2659 if GlobalData.gFdfParser:\r
2660 return path.join(self.PlatformInfo.BuildDir, TAB_FV_DIRECTORY, "Ffs", self.Guid + self.Name)\r
2661 return ''\r
37de70b7 2662\r
52302d4d 2663 ## Return the directory to store auto-gened source files of the mdoule\r
b23414f6
JC
2664 @cached_property\r
2665 def DebugDir(self):\r
2666 return _MakeDir((self.BuildDir, "DEBUG"))\r
52302d4d
LG
2667\r
2668 ## Return the path of custom file\r
b23414f6
JC
2669 @cached_property\r
2670 def CustomMakefile(self):\r
2671 RetVal = {}\r
2672 for Type in self.Module.CustomMakefile:\r
2673 MakeType = gMakeTypeMap[Type] if Type in gMakeTypeMap else 'nmake'\r
2674 if self.SourceOverrideDir is not None:\r
2675 File = os.path.join(self.SourceOverrideDir, self.Module.CustomMakefile[Type])\r
2676 if not os.path.exists(File):\r
52302d4d 2677 File = os.path.join(self.SourceDir, self.Module.CustomMakefile[Type])\r
b23414f6
JC
2678 else:\r
2679 File = os.path.join(self.SourceDir, self.Module.CustomMakefile[Type])\r
2680 RetVal[MakeType] = File\r
2681 return RetVal\r
52302d4d
LG
2682\r
2683 ## Return the directory of the makefile\r
2684 #\r
2685 # @retval string The directory string of module's makefile\r
2686 #\r
b23414f6
JC
2687 @cached_property\r
2688 def MakeFileDir(self):\r
52302d4d
LG
2689 return self.BuildDir\r
2690\r
2691 ## Return build command string\r
2692 #\r
2693 # @retval string Build command string\r
2694 #\r
b23414f6
JC
2695 @cached_property\r
2696 def BuildCommand(self):\r
52302d4d
LG
2697 return self.PlatformInfo.BuildCommand\r
2698\r
2699 ## Get object list of all packages the module and its dependent libraries belong to\r
2700 #\r
2701 # @retval list The list of package object\r
2702 #\r
b23414f6
JC
2703 @cached_property\r
2704 def DerivedPackageList(self):\r
52302d4d
LG
2705 PackageList = []\r
2706 for M in [self.Module] + self.DependentLibraryList:\r
2707 for Package in M.Packages:\r
2708 if Package in PackageList:\r
2709 continue\r
2710 PackageList.append(Package)\r
2711 return PackageList\r
f7496d71 2712\r
97fa0ee9
YL
2713 ## Get the depex string\r
2714 #\r
2715 # @return : a string contain all depex expresion.\r
2716 def _GetDepexExpresionString(self):\r
2717 DepexStr = ''\r
2718 DepexList = []\r
2719 ## DPX_SOURCE IN Define section.\r
2720 if self.Module.DxsFile:\r
2721 return DepexStr\r
2722 for M in [self.Module] + self.DependentLibraryList:\r
2723 Filename = M.MetaFile.Path\r
2724 InfObj = InfSectionParser.InfSectionParser(Filename)\r
2725 DepexExpresionList = InfObj.GetDepexExpresionList()\r
2726 for DepexExpresion in DepexExpresionList:\r
9eb87141 2727 for key in DepexExpresion:\r
97fa0ee9 2728 Arch, ModuleType = key\r
518aebe2 2729 DepexExpr = [x for x in DepexExpresion[key] if not str(x).startswith('#')]\r
97fa0ee9
YL
2730 # the type of build module is USER_DEFINED.\r
2731 # All different DEPEX section tags would be copied into the As Built INF file\r
2732 # and there would be separate DEPEX section tags\r
2733 if self.ModuleType.upper() == SUP_MODULE_USER_DEFINED:\r
2734 if (Arch.upper() == self.Arch.upper()) and (ModuleType.upper() != TAB_ARCH_COMMON):\r
518aebe2 2735 DepexList.append({(Arch, ModuleType): DepexExpr})\r
97fa0ee9
YL
2736 else:\r
2737 if Arch.upper() == TAB_ARCH_COMMON or \\r
2738 (Arch.upper() == self.Arch.upper() and \\r
2739 ModuleType.upper() in [TAB_ARCH_COMMON, self.ModuleType.upper()]):\r
518aebe2 2740 DepexList.append({(Arch, ModuleType): DepexExpr})\r
f7496d71 2741\r
97fa0ee9
YL
2742 #the type of build module is USER_DEFINED.\r
2743 if self.ModuleType.upper() == SUP_MODULE_USER_DEFINED:\r
2744 for Depex in DepexList:\r
9eb87141 2745 for key in Depex:\r
97fa0ee9 2746 DepexStr += '[Depex.%s.%s]\n' % key\r
8252e6bf 2747 DepexStr += '\n'.join('# '+ val for val in Depex[key])\r
97fa0ee9
YL
2748 DepexStr += '\n\n'\r
2749 if not DepexStr:\r
2750 return '[Depex.%s]\n' % self.Arch\r
2751 return DepexStr\r
f7496d71 2752\r
97fa0ee9
YL
2753 #the type of build module not is USER_DEFINED.\r
2754 Count = 0\r
2755 for Depex in DepexList:\r
2756 Count += 1\r
2757 if DepexStr != '':\r
2758 DepexStr += ' AND '\r
2759 DepexStr += '('\r
2760 for D in Depex.values():\r
8252e6bf 2761 DepexStr += ' '.join(val for val in D)\r
97fa0ee9
YL
2762 Index = DepexStr.find('END')\r
2763 if Index > -1 and Index == len(DepexStr) - 3:\r
2764 DepexStr = DepexStr[:-3]\r
2765 DepexStr = DepexStr.strip()\r
2766 DepexStr += ')'\r
2767 if Count == 1:\r
2768 DepexStr = DepexStr.lstrip('(').rstrip(')').strip()\r
2769 if not DepexStr:\r
2770 return '[Depex.%s]\n' % self.Arch\r
2771 return '[Depex.%s]\n# ' % self.Arch + DepexStr\r
f7496d71 2772\r
52302d4d
LG
2773 ## Merge dependency expression\r
2774 #\r
2775 # @retval list The token list of the dependency expression after parsed\r
2776 #\r
b23414f6
JC
2777 @cached_property\r
2778 def DepexList(self):\r
2779 if self.DxsFile or self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:\r
2780 return {}\r
2781\r
0258ba62
JC
2782 DepexList = []\r
2783 #\r
2784 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion\r
2785 #\r
2786 for M in [self.Module] + self.DependentLibraryList:\r
2787 Inherited = False\r
2788 for D in M.Depex[self.Arch, self.ModuleType]:\r
2789 if DepexList != []:\r
2790 DepexList.append('AND')\r
2791 DepexList.append('(')\r
2792 #replace D with value if D is FixedAtBuild PCD\r
2793 NewList = []\r
2794 for item in D:\r
2795 if '.' not in item:\r
2796 NewList.append(item)\r
2797 else:\r
2798 if item not in self._FixedPcdVoidTypeDict:\r
2799 EdkLogger.error("build", FORMAT_INVALID, "{} used in [Depex] section should be used as FixedAtBuild type and VOID* datum type in the module.".format(item))\r
b23414f6 2800 else:\r
0258ba62
JC
2801 Value = self._FixedPcdVoidTypeDict[item]\r
2802 if len(Value.split(',')) != 16:\r
2803 EdkLogger.error("build", FORMAT_INVALID,\r
2804 "{} used in [Depex] section should be used as FixedAtBuild type and VOID* datum type and 16 bytes in the module.".format(item))\r
2805 NewList.append(Value)\r
2806 DepexList.extend(NewList)\r
2807 if DepexList[-1] == 'END': # no need of a END at this time\r
2808 DepexList.pop()\r
2809 DepexList.append(')')\r
2810 Inherited = True\r
2811 if Inherited:\r
2812 EdkLogger.verbose("DEPEX[%s] (+%s) = %s" % (self.Name, M.BaseName, DepexList))\r
2813 if 'BEFORE' in DepexList or 'AFTER' in DepexList:\r
2814 break\r
2815 if len(DepexList) > 0:\r
2816 EdkLogger.verbose('')\r
2817 return {self.ModuleType:DepexList}\r
52302d4d
LG
2818\r
2819 ## Merge dependency expression\r
2820 #\r
2821 # @retval list The token list of the dependency expression after parsed\r
2822 #\r
b23414f6 2823 @cached_property\r
6cf6fed0 2824 def DepexExpressionDict(self):\r
b23414f6
JC
2825 if self.DxsFile or self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:\r
2826 return {}\r
52302d4d 2827\r
0258ba62
JC
2828 DepexExpressionString = ''\r
2829 #\r
2830 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion\r
2831 #\r
2832 for M in [self.Module] + self.DependentLibraryList:\r
2833 Inherited = False\r
2834 for D in M.DepexExpression[self.Arch, self.ModuleType]:\r
2835 if DepexExpressionString != '':\r
2836 DepexExpressionString += ' AND '\r
2837 DepexExpressionString += '('\r
2838 DepexExpressionString += D\r
2839 DepexExpressionString = DepexExpressionString.rstrip('END').strip()\r
2840 DepexExpressionString += ')'\r
2841 Inherited = True\r
2842 if Inherited:\r
2843 EdkLogger.verbose("DEPEX[%s] (+%s) = %s" % (self.Name, M.BaseName, DepexExpressionString))\r
2844 if 'BEFORE' in DepexExpressionString or 'AFTER' in DepexExpressionString:\r
2845 break\r
2846 if len(DepexExpressionString) > 0:\r
2847 EdkLogger.verbose('')\r
52302d4d 2848\r
0258ba62 2849 return {self.ModuleType:DepexExpressionString}\r
52302d4d 2850\r
dfa41b4a
YZ
2851 # Get the tiano core user extension, it is contain dependent library.\r
2852 # @retval: a list contain tiano core userextension.\r
2853 #\r
2854 def _GetTianoCoreUserExtensionList(self):\r
2855 TianoCoreUserExtentionList = []\r
2856 for M in [self.Module] + self.DependentLibraryList:\r
2857 Filename = M.MetaFile.Path\r
2858 InfObj = InfSectionParser.InfSectionParser(Filename)\r
2859 TianoCoreUserExtenList = InfObj.GetUserExtensionTianoCore()\r
2860 for TianoCoreUserExtent in TianoCoreUserExtenList:\r
9eb87141 2861 for Section in TianoCoreUserExtent:\r
dfa41b4a
YZ
2862 ItemList = Section.split(TAB_SPLIT)\r
2863 Arch = self.Arch\r
2864 if len(ItemList) == 4:\r
2865 Arch = ItemList[3]\r
2866 if Arch.upper() == TAB_ARCH_COMMON or Arch.upper() == self.Arch.upper():\r
2867 TianoCoreList = []\r
2868 TianoCoreList.extend([TAB_SECTION_START + Section + TAB_SECTION_END])\r
2869 TianoCoreList.extend(TianoCoreUserExtent[Section][:])\r
2870 TianoCoreList.append('\n')\r
2871 TianoCoreUserExtentionList.append(TianoCoreList)\r
2872\r
2873 return TianoCoreUserExtentionList\r
2874\r
52302d4d
LG
2875 ## Return the list of specification version required for the module\r
2876 #\r
2877 # @retval list The list of specification defined in module file\r
2878 #\r
b23414f6
JC
2879 @cached_property\r
2880 def Specification(self):\r
52302d4d
LG
2881 return self.Module.Specification\r
2882\r
2883 ## Tool option for the module build\r
2884 #\r
2885 # @param PlatformInfo The object of PlatformBuildInfo\r
2886 # @retval dict The dict containing valid options\r
2887 #\r
b23414f6
JC
2888 @cached_property\r
2889 def BuildOption(self):\r
2890 RetVal, self.BuildRuleOrder = self.PlatformInfo.ApplyBuildOption(self.Module)\r
2891 if self.BuildRuleOrder:\r
2892 self.BuildRuleOrder = ['.%s' % Ext for Ext in self.BuildRuleOrder.split()]\r
2893 return RetVal\r
52302d4d 2894\r
79b74a03
LG
2895 ## Get include path list from tool option for the module build\r
2896 #\r
2897 # @retval list The include path list\r
2898 #\r
b23414f6
JC
2899 @cached_property\r
2900 def BuildOptionIncPathList(self):\r
2901 #\r
2902 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT\r
2903 # is the former use /I , the Latter used -I to specify include directories\r
2904 #\r
94c04559 2905 if self.PlatformInfo.ToolChainFamily in (TAB_COMPILER_MSFT):\r
b23414f6
JC
2906 BuildOptIncludeRegEx = gBuildOptIncludePatternMsft\r
2907 elif self.PlatformInfo.ToolChainFamily in ('INTEL', 'GCC', 'RVCT'):\r
2908 BuildOptIncludeRegEx = gBuildOptIncludePatternOther\r
2909 else:\r
79b74a03 2910 #\r
b23414f6 2911 # New ToolChainFamily, don't known whether there is option to specify include directories\r
79b74a03 2912 #\r
b23414f6 2913 return []\r
f7496d71 2914\r
b23414f6
JC
2915 RetVal = []\r
2916 for Tool in ('CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'ASM'):\r
2917 try:\r
2918 FlagOption = self.BuildOption[Tool]['FLAGS']\r
2919 except KeyError:\r
2920 FlagOption = ''\r
d40b2ee6 2921\r
e6c62ab7 2922 if self.ToolChainFamily != 'RVCT':\r
b23414f6
JC
2923 IncPathList = [NormPath(Path, self.Macros) for Path in BuildOptIncludeRegEx.findall(FlagOption)]\r
2924 else:\r
79b74a03 2925 #\r
b23414f6 2926 # RVCT may specify a list of directory seperated by commas\r
79b74a03 2927 #\r
b23414f6
JC
2928 IncPathList = []\r
2929 for Path in BuildOptIncludeRegEx.findall(FlagOption):\r
2930 PathList = GetSplitList(Path, TAB_COMMA_SPLIT)\r
2931 IncPathList.extend(NormPath(PathEntry, self.Macros) for PathEntry in PathList)\r
f7496d71 2932\r
b23414f6
JC
2933 #\r
2934 # EDK II modules must not reference header files outside of the packages they depend on or\r
2935 # within the module's directory tree. Report error if violation.\r
2936 #\r
2937 if self.AutoGenVersion >= 0x00010005:\r
2938 for Path in IncPathList:\r
2939 if (Path not in self.IncludePathList) and (CommonPath([Path, self.MetaFile.Dir]) != self.MetaFile.Dir):\r
2940 ErrMsg = "The include directory for the EDK II module in this line is invalid %s specified in %s FLAGS '%s'" % (Path, Tool, FlagOption)\r
2941 EdkLogger.error("build",\r
2942 PARAMETER_INVALID,\r
2943 ExtraData=ErrMsg,\r
2944 File=str(self.MetaFile))\r
2945 RetVal += IncPathList\r
2946 return RetVal\r
f7496d71 2947\r
52302d4d
LG
2948 ## Return a list of files which can be built from source\r
2949 #\r
2950 # What kind of files can be built is determined by build rules in\r
97fa0ee9 2951 # $(CONF_DIRECTORY)/build_rule.txt and toolchain family.\r
52302d4d 2952 #\r
b23414f6
JC
2953 @cached_property\r
2954 def SourceFileList(self):\r
2955 RetVal = []\r
2956 ToolChainTagSet = {"", "*", self.ToolChain}\r
2957 ToolChainFamilySet = {"", "*", self.ToolChainFamily, self.BuildRuleFamily}\r
2958 for F in self.Module.Sources:\r
2959 # match tool chain\r
2960 if F.TagName not in ToolChainTagSet:\r
2961 EdkLogger.debug(EdkLogger.DEBUG_9, "The toolchain [%s] for processing file [%s] is found, "\r
2962 "but [%s] is currently used" % (F.TagName, str(F), self.ToolChain))\r
2963 continue\r
2964 # match tool chain family or build rule family\r
2965 if F.ToolChainFamily not in ToolChainFamilySet:\r
2966 EdkLogger.debug(\r
2967 EdkLogger.DEBUG_0,\r
2968 "The file [%s] must be built by tools of [%s], " \\r
2969 "but current toolchain family is [%s], buildrule family is [%s]" \\r
2970 % (str(F), F.ToolChainFamily, self.ToolChainFamily, self.BuildRuleFamily))\r
2971 continue\r
52302d4d 2972\r
b23414f6
JC
2973 # add the file path into search path list for file including\r
2974 if F.Dir not in self.IncludePathList and self.AutoGenVersion >= 0x00010005:\r
2975 self.IncludePathList.insert(0, F.Dir)\r
2976 RetVal.append(F)\r
4cb7bade 2977\r
b23414f6 2978 self._MatchBuildRuleOrder(RetVal)\r
4cb7bade 2979\r
b23414f6
JC
2980 for F in RetVal:\r
2981 self._ApplyBuildRule(F, TAB_UNKNOWN_FILE)\r
2982 return RetVal\r
52302d4d 2983\r
4cb7bade
YZ
2984 def _MatchBuildRuleOrder(self, FileList):\r
2985 Order_Dict = {}\r
b23414f6 2986 self.BuildOption\r
4cb7bade
YZ
2987 for SingleFile in FileList:\r
2988 if self.BuildRuleOrder and SingleFile.Ext in self.BuildRuleOrder and SingleFile.Ext in self.BuildRules:\r
2989 key = SingleFile.Path.split(SingleFile.Ext)[0]\r
2990 if key in Order_Dict:\r
2991 Order_Dict[key].append(SingleFile.Ext)\r
2992 else:\r
2993 Order_Dict[key] = [SingleFile.Ext]\r
2994\r
2995 RemoveList = []\r
2996 for F in Order_Dict:\r
2997 if len(Order_Dict[F]) > 1:\r
2998 Order_Dict[F].sort(key=lambda i: self.BuildRuleOrder.index(i))\r
2999 for Ext in Order_Dict[F][1:]:\r
3000 RemoveList.append(F + Ext)\r
f7496d71 3001\r
4cb7bade
YZ
3002 for item in RemoveList:\r
3003 FileList.remove(item)\r
3004\r
3005 return FileList\r
3006\r
52302d4d 3007 ## Return the list of unicode files\r
b23414f6
JC
3008 @cached_property\r
3009 def UnicodeFileList(self):\r
3010 return self.FileTypes.get(TAB_UNICODE_FILE,[])\r
52302d4d 3011\r
5b97eb4c 3012 ## Return the list of vfr files\r
b23414f6
JC
3013 @cached_property\r
3014 def VfrFileList(self):\r
3015 return self.FileTypes.get(TAB_VFR_FILE, [])\r
5b97eb4c 3016\r
333ba578 3017 ## Return the list of Image Definition files\r
b23414f6
JC
3018 @cached_property\r
3019 def IdfFileList(self):\r
3020 return self.FileTypes.get(TAB_IMAGE_FILE,[])\r
333ba578 3021\r
52302d4d
LG
3022 ## Return a list of files which can be built from binary\r
3023 #\r
3024 # "Build" binary files are just to copy them to build directory.\r
3025 #\r
3026 # @retval list The list of files which can be built later\r
3027 #\r
b23414f6
JC
3028 @cached_property\r
3029 def BinaryFileList(self):\r
3030 RetVal = []\r
3031 for F in self.Module.Binaries:\r
3032 if F.Target not in [TAB_ARCH_COMMON, '*'] and F.Target != self.BuildTarget:\r
3033 continue\r
3034 RetVal.append(F)\r
3035 self._ApplyBuildRule(F, F.Type, BinaryFileList=RetVal)\r
3036 return RetVal\r
3037\r
3038 @cached_property\r
3039 def BuildRules(self):\r
3040 RetVal = {}\r
3041 BuildRuleDatabase = self.PlatformInfo.BuildRule\r
3042 for Type in BuildRuleDatabase.FileTypeList:\r
3043 #first try getting build rule by BuildRuleFamily\r
3044 RuleObject = BuildRuleDatabase[Type, self.BuildType, self.Arch, self.BuildRuleFamily]\r
3045 if not RuleObject:\r
3046 # build type is always module type, but ...\r
3047 if self.ModuleType != self.BuildType:\r
3048 RuleObject = BuildRuleDatabase[Type, self.ModuleType, self.Arch, self.BuildRuleFamily]\r
3049 #second try getting build rule by ToolChainFamily\r
3050 if not RuleObject:\r
3051 RuleObject = BuildRuleDatabase[Type, self.BuildType, self.Arch, self.ToolChainFamily]\r
52302d4d
LG
3052 if not RuleObject:\r
3053 # build type is always module type, but ...\r
3054 if self.ModuleType != self.BuildType:\r
b23414f6
JC
3055 RuleObject = BuildRuleDatabase[Type, self.ModuleType, self.Arch, self.ToolChainFamily]\r
3056 if not RuleObject:\r
3057 continue\r
3058 RuleObject = RuleObject.Instantiate(self.Macros)\r
3059 RetVal[Type] = RuleObject\r
3060 for Ext in RuleObject.SourceFileExtList:\r
3061 RetVal[Ext] = RuleObject\r
3062 return RetVal\r
3063\r
3064 def _ApplyBuildRule(self, File, FileType, BinaryFileList=None):\r
4231a819 3065 if self._BuildTargets is None:\r
52302d4d
LG
3066 self._IntroBuildTargetList = set()\r
3067 self._FinalBuildTargetList = set()\r
a993dc03
CJ
3068 self._BuildTargets = defaultdict(set)\r
3069 self._FileTypes = defaultdict(set)\r
52302d4d 3070\r
b23414f6
JC
3071 if not BinaryFileList:\r
3072 BinaryFileList = self.BinaryFileList\r
3073\r
fcd4fbf3
YL
3074 SubDirectory = os.path.join(self.OutputDir, File.SubDir)\r
3075 if not os.path.exists(SubDirectory):\r
3076 CreateDirectory(SubDirectory)\r
52302d4d 3077 LastTarget = None\r
caf74495 3078 RuleChain = set()\r
52302d4d
LG
3079 SourceList = [File]\r
3080 Index = 0\r
fe4bf2f9
YL
3081 #\r
3082 # Make sure to get build rule order value\r
3083 #\r
b23414f6 3084 self.BuildOption\r
fe4bf2f9 3085\r
52302d4d
LG
3086 while Index < len(SourceList):\r
3087 Source = SourceList[Index]\r
3088 Index = Index + 1\r
3089\r
3090 if Source != File:\r
3091 CreateDirectory(Source.Dir)\r
3092\r
b23414f6 3093 if File.IsBinary and File == Source and File in BinaryFileList:\r
da92f276
LG
3094 # Skip all files that are not binary libraries\r
3095 if not self.IsLibrary:\r
47fea6af 3096 continue\r
52302d4d
LG
3097 RuleObject = self.BuildRules[TAB_DEFAULT_BINARY_FILE]\r
3098 elif FileType in self.BuildRules:\r
3099 RuleObject = self.BuildRules[FileType]\r
3100 elif Source.Ext in self.BuildRules:\r
3101 RuleObject = self.BuildRules[Source.Ext]\r
3102 else:\r
3103 # stop at no more rules\r
3104 if LastTarget:\r
3105 self._FinalBuildTargetList.add(LastTarget)\r
3106 break\r
3107\r
3108 FileType = RuleObject.SourceFileType\r
52302d4d
LG
3109 self._FileTypes[FileType].add(Source)\r
3110\r
3111 # stop at STATIC_LIBRARY for library\r
3112 if self.IsLibrary and FileType == TAB_STATIC_LIBRARY:\r
3113 if LastTarget:\r
3114 self._FinalBuildTargetList.add(LastTarget)\r
3115 break\r
3116\r
fe4bf2f9 3117 Target = RuleObject.Apply(Source, self.BuildRuleOrder)\r
52302d4d
LG
3118 if not Target:\r
3119 if LastTarget:\r
3120 self._FinalBuildTargetList.add(LastTarget)\r
3121 break\r
3122 elif not Target.Outputs:\r
3123 # Only do build for target with outputs\r
3124 self._FinalBuildTargetList.add(Target)\r
3125\r
52302d4d
LG
3126 self._BuildTargets[FileType].add(Target)\r
3127\r
3128 if not Source.IsBinary and Source == File:\r
3129 self._IntroBuildTargetList.add(Target)\r
3130\r
3131 # to avoid cyclic rule\r
3132 if FileType in RuleChain:\r
3133 break\r
3134\r
caf74495 3135 RuleChain.add(FileType)\r
52302d4d
LG
3136 SourceList.extend(Target.Outputs)\r
3137 LastTarget = Target\r
3138 FileType = TAB_UNKNOWN_FILE\r
3139\r
b23414f6
JC
3140 @cached_property\r
3141 def Targets(self):\r
4231a819 3142 if self._BuildTargets is None:\r
52302d4d
LG
3143 self._IntroBuildTargetList = set()\r
3144 self._FinalBuildTargetList = set()\r
a993dc03
CJ
3145 self._BuildTargets = defaultdict(set)\r
3146 self._FileTypes = defaultdict(set)\r
52302d4d 3147\r
b23414f6
JC
3148 #TRICK: call SourceFileList property to apply build rule for source files\r
3149 self.SourceFileList\r
52302d4d
LG
3150\r
3151 #TRICK: call _GetBinaryFileList to apply build rule for binary files\r
b23414f6 3152 self.BinaryFileList\r
52302d4d
LG
3153\r
3154 return self._BuildTargets\r
3155\r
b23414f6
JC
3156 @cached_property\r
3157 def IntroTargetList(self):\r
3158 self.Targets\r
52302d4d
LG
3159 return self._IntroBuildTargetList\r
3160\r
b23414f6
JC
3161 @cached_property\r
3162 def CodaTargetList(self):\r
3163 self.Targets\r
52302d4d
LG
3164 return self._FinalBuildTargetList\r
3165\r
b23414f6
JC
3166 @cached_property\r
3167 def FileTypes(self):\r
3168 self.Targets\r
52302d4d
LG
3169 return self._FileTypes\r
3170\r
3171 ## Get the list of package object the module depends on\r
3172 #\r
3173 # @retval list The package object list\r
3174 #\r
b23414f6
JC
3175 @cached_property\r
3176 def DependentPackageList(self):\r
52302d4d
LG
3177 return self.Module.Packages\r
3178\r
3179 ## Return the list of auto-generated code file\r
3180 #\r
3181 # @retval list The list of auto-generated file\r
3182 #\r
b23414f6
JC
3183 @cached_property\r
3184 def AutoGenFileList(self):\r
3185 AutoGenUniIdf = self.BuildType != 'UEFI_HII'\r
86379ac4
GL
3186 UniStringBinBuffer = BytesIO()\r
3187 IdfGenBinBuffer = BytesIO()\r
b23414f6
JC
3188 RetVal = {}\r
3189 AutoGenC = TemplateString()\r
3190 AutoGenH = TemplateString()\r
3191 StringH = TemplateString()\r
3192 StringIdf = TemplateString()\r
3193 GenC.CreateCode(self, AutoGenC, AutoGenH, StringH, AutoGenUniIdf, UniStringBinBuffer, StringIdf, AutoGenUniIdf, IdfGenBinBuffer)\r
3194 #\r
3195 # AutoGen.c is generated if there are library classes in inf, or there are object files\r
3196 #\r
3197 if str(AutoGenC) != "" and (len(self.Module.LibraryClasses) > 0\r
3198 or TAB_OBJECT_FILE in self.FileTypes):\r
3199 AutoFile = PathClass(gAutoGenCodeFileName, self.DebugDir)\r
3200 RetVal[AutoFile] = str(AutoGenC)\r
3201 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
3202 if str(AutoGenH) != "":\r
3203 AutoFile = PathClass(gAutoGenHeaderFileName, self.DebugDir)\r
3204 RetVal[AutoFile] = str(AutoGenH)\r
3205 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
3206 if str(StringH) != "":\r
3207 AutoFile = PathClass(gAutoGenStringFileName % {"module_name":self.Name}, self.DebugDir)\r
3208 RetVal[AutoFile] = str(StringH)\r
3209 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
86e6cf98 3210 if UniStringBinBuffer is not None and UniStringBinBuffer.getvalue() != b"":\r
b23414f6
JC
3211 AutoFile = PathClass(gAutoGenStringFormFileName % {"module_name":self.Name}, self.OutputDir)\r
3212 RetVal[AutoFile] = UniStringBinBuffer.getvalue()\r
3213 AutoFile.IsBinary = True\r
3214 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
3215 if UniStringBinBuffer is not None:\r
3216 UniStringBinBuffer.close()\r
3217 if str(StringIdf) != "":\r
3218 AutoFile = PathClass(gAutoGenImageDefFileName % {"module_name":self.Name}, self.DebugDir)\r
3219 RetVal[AutoFile] = str(StringIdf)\r
3220 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
86e6cf98 3221 if IdfGenBinBuffer is not None and IdfGenBinBuffer.getvalue() != b"":\r
b23414f6
JC
3222 AutoFile = PathClass(gAutoGenIdfFileName % {"module_name":self.Name}, self.OutputDir)\r
3223 RetVal[AutoFile] = IdfGenBinBuffer.getvalue()\r
3224 AutoFile.IsBinary = True\r
3225 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
3226 if IdfGenBinBuffer is not None:\r
3227 IdfGenBinBuffer.close()\r
3228 return RetVal\r
52302d4d
LG
3229\r
3230 ## Return the list of library modules explicitly or implicityly used by this module\r
b23414f6
JC
3231 @cached_property\r
3232 def DependentLibraryList(self):\r
3233 # only merge library classes and PCD for non-library module\r
3234 if self.IsLibrary:\r
3235 return []\r
3236 if self.AutoGenVersion < 0x00010005:\r
3237 return self.PlatformInfo.ResolveLibraryReference(self.Module)\r
3238 return self.PlatformInfo.ApplyLibraryInstance(self.Module)\r
52302d4d
LG
3239\r
3240 ## Get the list of PCDs from current module\r
3241 #\r
3242 # @retval list The list of PCD\r
3243 #\r
b23414f6
JC
3244 @cached_property\r
3245 def ModulePcdList(self):\r
3246 # apply PCD settings from platform\r
3247 RetVal = self.PlatformInfo.ApplyPcdSetting(self.Module, self.Module.Pcds)\r
3248 ExtendCopyDictionaryLists(self._PcdComments, self.Module.PcdComments)\r
3249 return RetVal\r
52302d4d
LG
3250\r
3251 ## Get the list of PCDs from dependent libraries\r
3252 #\r
3253 # @retval list The list of PCD\r
3254 #\r
b23414f6
JC
3255 @cached_property\r
3256 def LibraryPcdList(self):\r
3257 if self.IsLibrary:\r
3258 return []\r
3259 RetVal = []\r
3260 Pcds = set()\r
3261 # get PCDs from dependent libraries\r
3262 for Library in self.DependentLibraryList:\r
3263 PcdsInLibrary = OrderedDict()\r
3264 ExtendCopyDictionaryLists(self._PcdComments, Library.PcdComments)\r
3265 for Key in Library.Pcds:\r
3266 # skip duplicated PCDs\r
3267 if Key in self.Module.Pcds or Key in Pcds:\r
3268 continue\r
3269 Pcds.add(Key)\r
3270 PcdsInLibrary[Key] = copy.copy(Library.Pcds[Key])\r
3271 RetVal.extend(self.PlatformInfo.ApplyPcdSetting(self.Module, PcdsInLibrary, Library=Library))\r
3272 return RetVal\r
52302d4d
LG
3273\r
3274 ## Get the GUID value mapping\r
3275 #\r
3276 # @retval dict The mapping between GUID cname and its value\r
3277 #\r
b23414f6
JC
3278 @cached_property\r
3279 def GuidList(self):\r
3280 RetVal = OrderedDict(self.Module.Guids)\r
3281 for Library in self.DependentLibraryList:\r
3282 RetVal.update(Library.Guids)\r
3283 ExtendCopyDictionaryLists(self._GuidComments, Library.GuidComments)\r
3284 ExtendCopyDictionaryLists(self._GuidComments, self.Module.GuidComments)\r
3285 return RetVal\r
3286\r
3287 @cached_property\r
e8a47801 3288 def GetGuidsUsedByPcd(self):\r
b23414f6
JC
3289 RetVal = OrderedDict(self.Module.GetGuidsUsedByPcd())\r
3290 for Library in self.DependentLibraryList:\r
3291 RetVal.update(Library.GetGuidsUsedByPcd())\r
3292 return RetVal\r
52302d4d
LG
3293 ## Get the protocol value mapping\r
3294 #\r
3295 # @retval dict The mapping between protocol cname and its value\r
3296 #\r
b23414f6
JC
3297 @cached_property\r
3298 def ProtocolList(self):\r
3299 RetVal = OrderedDict(self.Module.Protocols)\r
3300 for Library in self.DependentLibraryList:\r
3301 RetVal.update(Library.Protocols)\r
3302 ExtendCopyDictionaryLists(self._ProtocolComments, Library.ProtocolComments)\r
3303 ExtendCopyDictionaryLists(self._ProtocolComments, self.Module.ProtocolComments)\r
3304 return RetVal\r
52302d4d
LG
3305\r
3306 ## Get the PPI value mapping\r
3307 #\r
3308 # @retval dict The mapping between PPI cname and its value\r
3309 #\r
b23414f6
JC
3310 @cached_property\r
3311 def PpiList(self):\r
3312 RetVal = OrderedDict(self.Module.Ppis)\r
3313 for Library in self.DependentLibraryList:\r
3314 RetVal.update(Library.Ppis)\r
3315 ExtendCopyDictionaryLists(self._PpiComments, Library.PpiComments)\r
3316 ExtendCopyDictionaryLists(self._PpiComments, self.Module.PpiComments)\r
3317 return RetVal\r
52302d4d
LG
3318\r
3319 ## Get the list of include search path\r
3320 #\r
3321 # @retval list The list path\r
3322 #\r
b23414f6
JC
3323 @cached_property\r
3324 def IncludePathList(self):\r
3325 RetVal = []\r
3326 if self.AutoGenVersion < 0x00010005:\r
3327 for Inc in self.Module.Includes:\r
3328 if Inc not in RetVal:\r
3329 RetVal.append(Inc)\r
3330 # for Edk modules\r
3331 Inc = path.join(Inc, self.Arch.capitalize())\r
3332 if os.path.exists(Inc) and Inc not in RetVal:\r
3333 RetVal.append(Inc)\r
3334 # Edk module needs to put DEBUG_DIR at the end of search path and not to use SOURCE_DIR all the time\r
3335 RetVal.append(self.DebugDir)\r
3336 else:\r
3337 RetVal.append(self.MetaFile.Dir)\r
3338 RetVal.append(self.DebugDir)\r
3339\r
3340 for Package in self.Module.Packages:\r
3341 PackageDir = mws.join(self.WorkspaceDir, Package.MetaFile.Dir)\r
3342 if PackageDir not in RetVal:\r
3343 RetVal.append(PackageDir)\r
3344 IncludesList = Package.Includes\r
3345 if Package._PrivateIncludes:\r
3346 if not self.MetaFile.Path.startswith(PackageDir):\r
3347 IncludesList = list(set(Package.Includes).difference(set(Package._PrivateIncludes)))\r
3348 for Inc in IncludesList:\r
3349 if Inc not in RetVal:\r
3350 RetVal.append(str(Inc))\r
3351 return RetVal\r
3352\r
3353 @cached_property\r
3354 def IncludePathLength(self):\r
3355 return sum(len(inc)+1 for inc in self.IncludePathList)\r
725cdb8f 3356\r
97fa0ee9
YL
3357 ## Get HII EX PCDs which maybe used by VFR\r
3358 #\r
3359 # efivarstore used by VFR may relate with HII EX PCDs\r
3360 # Get the variable name and GUID from efivarstore and HII EX PCD\r
3361 # List the HII EX PCDs in As Built INF if both name and GUID match.\r
3362 #\r
3363 # @retval list HII EX PCDs\r
3364 #\r
3365 def _GetPcdsMaybeUsedByVfr(self):\r
3366 if not self.SourceFileList:\r
3367 return []\r
3368\r
29189291 3369 NameGuids = set()\r
97fa0ee9
YL
3370 for SrcFile in self.SourceFileList:\r
3371 if SrcFile.Ext.lower() != '.vfr':\r
3372 continue\r
3373 Vfri = os.path.join(self.OutputDir, SrcFile.BaseName + '.i')\r
3374 if not os.path.exists(Vfri):\r
3375 continue\r
3376 VfriFile = open(Vfri, 'r')\r
3377 Content = VfriFile.read()\r
3378 VfriFile.close()\r
3379 Pos = Content.find('efivarstore')\r
3380 while Pos != -1:\r
3381 #\r
3382 # Make sure 'efivarstore' is the start of efivarstore statement\r
3383 # In case of the value of 'name' (name = efivarstore) is equal to 'efivarstore'\r
3384 #\r
3385 Index = Pos - 1\r
3386 while Index >= 0 and Content[Index] in ' \t\r\n':\r
3387 Index -= 1\r
3388 if Index >= 0 and Content[Index] != ';':\r
3389 Pos = Content.find('efivarstore', Pos + len('efivarstore'))\r
3390 continue\r
3391 #\r
3392 # 'efivarstore' must be followed by name and guid\r
3393 #\r
3394 Name = gEfiVarStoreNamePattern.search(Content, Pos)\r
3395 if not Name:\r
3396 break\r
3397 Guid = gEfiVarStoreGuidPattern.search(Content, Pos)\r
3398 if not Guid:\r
3399 break\r
3400 NameArray = ConvertStringToByteArray('L"' + Name.group(1) + '"')\r
29189291 3401 NameGuids.add((NameArray, GuidStructureStringToGuidString(Guid.group(1))))\r
97fa0ee9
YL
3402 Pos = Content.find('efivarstore', Name.end())\r
3403 if not NameGuids:\r
3404 return []\r
3405 HiiExPcds = []\r
3406 for Pcd in self.PlatformInfo.Platform.Pcds.values():\r
3407 if Pcd.Type != TAB_PCDS_DYNAMIC_EX_HII:\r
3408 continue\r
caf74495 3409 for SkuInfo in Pcd.SkuInfoList.values():\r
c28d2e10 3410 Value = GuidValue(SkuInfo.VariableGuid, self.PlatformInfo.PackageList, self.MetaFile.Path)\r
97fa0ee9
YL
3411 if not Value:\r
3412 continue\r
caf74495 3413 Name = ConvertStringToByteArray(SkuInfo.VariableName)\r
97fa0ee9
YL
3414 Guid = GuidStructureStringToGuidString(Value)\r
3415 if (Name, Guid) in NameGuids and Pcd not in HiiExPcds:\r
3416 HiiExPcds.append(Pcd)\r
3417 break\r
3418\r
3419 return HiiExPcds\r
3420\r
aeaaf754
YL
3421 def _GenOffsetBin(self):\r
3422 VfrUniBaseName = {}\r
3423 for SourceFile in self.Module.Sources:\r
3424 if SourceFile.Type.upper() == ".VFR" :\r
3425 #\r
f7496d71 3426 # search the .map file to find the offset of vfr binary in the PE32+/TE file.\r
aeaaf754
YL
3427 #\r
3428 VfrUniBaseName[SourceFile.BaseName] = (SourceFile.BaseName + "Bin")\r
caf74495 3429 elif SourceFile.Type.upper() == ".UNI" :\r
aeaaf754 3430 #\r
f7496d71 3431 # search the .map file to find the offset of Uni strings binary in the PE32+/TE file.\r
aeaaf754
YL
3432 #\r
3433 VfrUniBaseName["UniOffsetName"] = (self.Name + "Strings")\r
3434\r
caf74495 3435 if not VfrUniBaseName:\r
aeaaf754
YL
3436 return None\r
3437 MapFileName = os.path.join(self.OutputDir, self.Name + ".map")\r
3438 EfiFileName = os.path.join(self.OutputDir, self.Name + ".efi")\r
3439 VfrUniOffsetList = GetVariableOffset(MapFileName, EfiFileName, VfrUniBaseName.values())\r
3440 if not VfrUniOffsetList:\r
3441 return None\r
3442\r
3443 OutputName = '%sOffset.bin' % self.Name\r
3444 UniVfrOffsetFileName = os.path.join( self.OutputDir, OutputName)\r
3445\r
3446 try:\r
3447 fInputfile = open(UniVfrOffsetFileName, "wb+", 0)\r
3448 except:\r
ccaa7754 3449 EdkLogger.error("build", FILE_OPEN_FAILURE, "File open failed for %s" % UniVfrOffsetFileName, None)\r
aeaaf754 3450\r
86379ac4 3451 # Use a instance of BytesIO to cache data\r
86e6cf98 3452 fStringIO = BytesIO()\r
aeaaf754
YL
3453\r
3454 for Item in VfrUniOffsetList:\r
3455 if (Item[0].find("Strings") != -1):\r
3456 #\r
3457 # UNI offset in image.\r
3458 # GUID + Offset\r
3459 # { 0x8913c5e0, 0x33f6, 0x4d86, { 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66 } }\r
3460 #\r
3461 UniGuid = [0xe0, 0xc5, 0x13, 0x89, 0xf6, 0x33, 0x86, 0x4d, 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66]\r
86e6cf98 3462 fStringIO.write(bytes(UniGuid))\r
aeaaf754
YL
3463 UniValue = pack ('Q', int (Item[1], 16))\r
3464 fStringIO.write (UniValue)\r
3465 else:\r
3466 #\r
3467 # VFR binary offset in image.\r
3468 # GUID + Offset\r
3469 # { 0xd0bc7cb4, 0x6a47, 0x495f, { 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2 } };\r
3470 #\r
3471 VfrGuid = [0xb4, 0x7c, 0xbc, 0xd0, 0x47, 0x6a, 0x5f, 0x49, 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2]\r
86e6cf98 3472 fStringIO.write(bytes(VfrGuid))\r
aeaaf754
YL
3473 VfrValue = pack ('Q', int (Item[1], 16))\r
3474 fStringIO.write (VfrValue)\r
3475 #\r
3476 # write data into file.\r
3477 #\r
f7496d71 3478 try :\r
aeaaf754
YL
3479 fInputfile.write (fStringIO.getvalue())\r
3480 except:\r
3481 EdkLogger.error("build", FILE_WRITE_FAILURE, "Write data to file %s failed, please check whether the "\r
ccaa7754 3482 "file been locked or using by other applications." %UniVfrOffsetFileName, None)\r
aeaaf754
YL
3483\r
3484 fStringIO.close ()\r
3485 fInputfile.close ()\r
3486 return OutputName\r
3487\r
da92f276
LG
3488 ## Create AsBuilt INF file the module\r
3489 #\r
83397f95 3490 def CreateAsBuiltInf(self, IsOnlyCopy = False):\r
ac55e478 3491 self.OutputFile = set()\r
caf74495
JC
3492 if IsOnlyCopy and GlobalData.gBinCacheDest:\r
3493 self.CopyModuleToCache()\r
3494 return\r
83397f95 3495\r
da92f276
LG
3496 if self.IsAsBuiltInfCreated:\r
3497 return\r
f7496d71 3498\r
da92f276
LG
3499 # Skip the following code for EDK I inf\r
3500 if self.AutoGenVersion < 0x00010005:\r
3501 return\r
f7496d71 3502\r
da92f276
LG
3503 # Skip the following code for libraries\r
3504 if self.IsLibrary:\r
3505 return\r
f7496d71 3506\r
da92f276 3507 # Skip the following code for modules with no source files\r
6be94743 3508 if not self.SourceFileList:\r
da92f276
LG
3509 return\r
3510\r
3511 # Skip the following code for modules without any binary files\r
40857777 3512 if self.BinaryFileList:\r
da92f276 3513 return\r
f7496d71 3514\r
da92f276
LG
3515 ### TODO: How to handles mixed source and binary modules\r
3516\r
e8a47801 3517 # Find all DynamicEx and PatchableInModule PCDs used by this module and dependent libraries\r
da92f276
LG
3518 # Also find all packages that the DynamicEx PCDs depend on\r
3519 Pcds = []\r
e5cf9198 3520 PatchablePcds = []\r
47fea6af 3521 Packages = []\r
e8a47801
LG
3522 PcdCheckList = []\r
3523 PcdTokenSpaceList = []\r
da92f276 3524 for Pcd in self.ModulePcdList + self.LibraryPcdList:\r
e8a47801 3525 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:\r
caf74495 3526 PatchablePcds.append(Pcd)\r
6b1f2cf4 3527 PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, TAB_PCDS_PATCHABLE_IN_MODULE))\r
eece4292 3528 elif Pcd.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
e8a47801 3529 if Pcd not in Pcds:\r
caf74495 3530 Pcds.append(Pcd)\r
6b1f2cf4
CJ
3531 PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC_EX))\r
3532 PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC))\r
e8a47801 3533 PcdTokenSpaceList.append(Pcd.TokenSpaceGuidCName)\r
b23414f6
JC
3534 GuidList = OrderedDict(self.GuidList)\r
3535 for TokenSpace in self.GetGuidsUsedByPcd:\r
e8a47801
LG
3536 # If token space is not referred by patch PCD or Ex PCD, remove the GUID from GUID list\r
3537 # The GUIDs in GUIDs section should really be the GUIDs in source INF or referred by Ex an patch PCDs\r
3538 if TokenSpace not in PcdTokenSpaceList and TokenSpace in GuidList:\r
3539 GuidList.pop(TokenSpace)\r
3540 CheckList = (GuidList, self.PpiList, self.ProtocolList, PcdCheckList)\r
3541 for Package in self.DerivedPackageList:\r
3542 if Package in Packages:\r
3543 continue\r
3544 BeChecked = (Package.Guids, Package.Ppis, Package.Protocols, Package.Pcds)\r
3545 Found = False\r
3546 for Index in range(len(BeChecked)):\r
3547 for Item in CheckList[Index]:\r
3548 if Item in BeChecked[Index]:\r
caf74495 3549 Packages.append(Package)\r
e8a47801
LG
3550 Found = True\r
3551 break\r
caf74495
JC
3552 if Found:\r
3553 break\r
da92f276 3554\r
97fa0ee9
YL
3555 VfrPcds = self._GetPcdsMaybeUsedByVfr()\r
3556 for Pkg in self.PlatformInfo.PackageList:\r
3557 if Pkg in Packages:\r
3558 continue\r
3559 for VfrPcd in VfrPcds:\r
6b1f2cf4
CJ
3560 if ((VfrPcd.TokenCName, VfrPcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC_EX) in Pkg.Pcds or\r
3561 (VfrPcd.TokenCName, VfrPcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC) in Pkg.Pcds):\r
caf74495 3562 Packages.append(Pkg)\r
97fa0ee9
YL
3563 break\r
3564\r
caf74495
JC
3565 ModuleType = SUP_MODULE_DXE_DRIVER if self.ModuleType == SUP_MODULE_UEFI_DRIVER and self.DepexGenerated else self.ModuleType\r
3566 DriverType = self.PcdIsDriver if self.PcdIsDriver else ''\r
97fa0ee9
YL
3567 Guid = self.Guid\r
3568 MDefs = self.Module.Defines\r
3569\r
da92f276
LG
3570 AsBuiltInfDict = {\r
3571 'module_name' : self.Name,\r
97fa0ee9 3572 'module_guid' : Guid,\r
da92f276 3573 'module_module_type' : ModuleType,\r
97fa0ee9 3574 'module_version_string' : [MDefs['VERSION_STRING']] if 'VERSION_STRING' in MDefs else [],\r
e8a47801 3575 'pcd_is_driver_string' : [],\r
da92f276
LG
3576 'module_uefi_specification_version' : [],\r
3577 'module_pi_specification_version' : [],\r
97fa0ee9
YL
3578 'module_entry_point' : self.Module.ModuleEntryPointList,\r
3579 'module_unload_image' : self.Module.ModuleUnloadImageList,\r
3580 'module_constructor' : self.Module.ConstructorList,\r
3581 'module_destructor' : self.Module.DestructorList,\r
3582 'module_shadow' : [MDefs['SHADOW']] if 'SHADOW' in MDefs else [],\r
3583 'module_pci_vendor_id' : [MDefs['PCI_VENDOR_ID']] if 'PCI_VENDOR_ID' in MDefs else [],\r
3584 'module_pci_device_id' : [MDefs['PCI_DEVICE_ID']] if 'PCI_DEVICE_ID' in MDefs else [],\r
3585 'module_pci_class_code' : [MDefs['PCI_CLASS_CODE']] if 'PCI_CLASS_CODE' in MDefs else [],\r
3586 'module_pci_revision' : [MDefs['PCI_REVISION']] if 'PCI_REVISION' in MDefs else [],\r
3587 'module_build_number' : [MDefs['BUILD_NUMBER']] if 'BUILD_NUMBER' in MDefs else [],\r
3588 'module_spec' : [MDefs['SPEC']] if 'SPEC' in MDefs else [],\r
3589 'module_uefi_hii_resource_section' : [MDefs['UEFI_HII_RESOURCE_SECTION']] if 'UEFI_HII_RESOURCE_SECTION' in MDefs else [],\r
3590 'module_uni_file' : [MDefs['MODULE_UNI_FILE']] if 'MODULE_UNI_FILE' in MDefs else [],\r
da92f276 3591 'module_arch' : self.Arch,\r
caf74495 3592 'package_item' : [Package.MetaFile.File.replace('\\', '/') for Package in Packages],\r
da92f276 3593 'binary_item' : [],\r
e8a47801 3594 'patchablepcd_item' : [],\r
da92f276 3595 'pcd_item' : [],\r
e8a47801
LG
3596 'protocol_item' : [],\r
3597 'ppi_item' : [],\r
3598 'guid_item' : [],\r
3599 'flags_item' : [],\r
3600 'libraryclasses_item' : []\r
da92f276 3601 }\r
97fa0ee9 3602\r
78bcd52a
YZ
3603 if 'MODULE_UNI_FILE' in MDefs:\r
3604 UNIFile = os.path.join(self.MetaFile.Dir, MDefs['MODULE_UNI_FILE'])\r
3605 if os.path.isfile(UNIFile):\r
3606 shutil.copy2(UNIFile, self.OutputDir)\r
3607\r
97fa0ee9
YL
3608 if self.AutoGenVersion > int(gInfSpecVersion, 0):\r
3609 AsBuiltInfDict['module_inf_version'] = '0x%08x' % self.AutoGenVersion\r
3610 else:\r
3611 AsBuiltInfDict['module_inf_version'] = gInfSpecVersion\r
3612\r
e8a47801 3613 if DriverType:\r
caf74495 3614 AsBuiltInfDict['pcd_is_driver_string'].append(DriverType)\r
da92f276
LG
3615\r
3616 if 'UEFI_SPECIFICATION_VERSION' in self.Specification:\r
caf74495 3617 AsBuiltInfDict['module_uefi_specification_version'].append(self.Specification['UEFI_SPECIFICATION_VERSION'])\r
da92f276 3618 if 'PI_SPECIFICATION_VERSION' in self.Specification:\r
caf74495 3619 AsBuiltInfDict['module_pi_specification_version'].append(self.Specification['PI_SPECIFICATION_VERSION'])\r
da92f276 3620\r
47fea6af 3621 OutputDir = self.OutputDir.replace('\\', '/').strip('/')\r
c7c5a6c4 3622 DebugDir = self.DebugDir.replace('\\', '/').strip('/')\r
481252bb 3623 for Item in self.CodaTargetList:\r
90456c3c 3624 File = Item.Target.Path.replace('\\', '/').strip('/').replace(DebugDir, '').replace(OutputDir, '').strip('/')\r
ac55e478 3625 self.OutputFile.add(File)\r
5e2c0ecd
YZ
3626 if os.path.isabs(File):\r
3627 File = File.replace('\\', '/').strip('/').replace(OutputDir, '').strip('/')\r
47fea6af 3628 if Item.Target.Ext.lower() == '.aml':\r
caf74495 3629 AsBuiltInfDict['binary_item'].append('ASL|' + File)\r
47fea6af 3630 elif Item.Target.Ext.lower() == '.acpi':\r
caf74495 3631 AsBuiltInfDict['binary_item'].append('ACPI|' + File)\r
481252bb 3632 elif Item.Target.Ext.lower() == '.efi':\r
caf74495 3633 AsBuiltInfDict['binary_item'].append('PE32|' + self.Name + '.efi')\r
da92f276 3634 else:\r
caf74495 3635 AsBuiltInfDict['binary_item'].append('BIN|' + File)\r
481252bb 3636 if self.DepexGenerated:\r
ac55e478 3637 self.OutputFile.add(self.Name + '.depex')\r
8bb63e37 3638 if self.ModuleType in [SUP_MODULE_PEIM]:\r
caf74495
JC
3639 AsBuiltInfDict['binary_item'].append('PEI_DEPEX|' + self.Name + '.depex')\r
3640 elif self.ModuleType in [SUP_MODULE_DXE_DRIVER, SUP_MODULE_DXE_RUNTIME_DRIVER, SUP_MODULE_DXE_SAL_DRIVER, SUP_MODULE_UEFI_DRIVER]:\r
3641 AsBuiltInfDict['binary_item'].append('DXE_DEPEX|' + self.Name + '.depex')\r
3642 elif self.ModuleType in [SUP_MODULE_DXE_SMM_DRIVER]:\r
3643 AsBuiltInfDict['binary_item'].append('SMM_DEPEX|' + self.Name + '.depex')\r
da92f276 3644\r
aeaaf754
YL
3645 Bin = self._GenOffsetBin()\r
3646 if Bin:\r
caf74495 3647 AsBuiltInfDict['binary_item'].append('BIN|%s' % Bin)\r
ac55e478 3648 self.OutputFile.add(Bin)\r
aeaaf754 3649\r
e8a47801
LG
3650 for Root, Dirs, Files in os.walk(OutputDir):\r
3651 for File in Files:\r
3652 if File.lower().endswith('.pdb'):\r
caf74495 3653 AsBuiltInfDict['binary_item'].append('DISPOSABLE|' + File)\r
ac55e478 3654 self.OutputFile.add(File)\r
e8a47801
LG
3655 HeaderComments = self.Module.HeaderComments\r
3656 StartPos = 0\r
3657 for Index in range(len(HeaderComments)):\r
3658 if HeaderComments[Index].find('@BinaryHeader') != -1:\r
3659 HeaderComments[Index] = HeaderComments[Index].replace('@BinaryHeader', '@file')\r
3660 StartPos = Index\r
3661 break\r
3662 AsBuiltInfDict['header_comments'] = '\n'.join(HeaderComments[StartPos:]).replace(':#', '://')\r
97fa0ee9
YL
3663 AsBuiltInfDict['tail_comments'] = '\n'.join(self.Module.TailComments)\r
3664\r
e8a47801
LG
3665 GenList = [\r
3666 (self.ProtocolList, self._ProtocolComments, 'protocol_item'),\r
3667 (self.PpiList, self._PpiComments, 'ppi_item'),\r
3668 (GuidList, self._GuidComments, 'guid_item')\r
3669 ]\r
3670 for Item in GenList:\r
3671 for CName in Item[0]:\r
caf74495
JC
3672 Comments = '\n '.join(Item[1][CName]) if CName in Item[1] else ''\r
3673 Entry = Comments + '\n ' + CName if Comments else CName\r
e8a47801
LG
3674 AsBuiltInfDict[Item[2]].append(Entry)\r
3675 PatchList = parsePcdInfoFromMapFile(\r
3676 os.path.join(self.OutputDir, self.Name + '.map'),\r
3677 os.path.join(self.OutputDir, self.Name + '.efi')\r
3678 )\r
3679 if PatchList:\r
e5cf9198
YZ
3680 for Pcd in PatchablePcds:\r
3681 TokenCName = Pcd.TokenCName\r
3682 for PcdItem in GlobalData.MixedPcd:\r
3683 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:\r
3684 TokenCName = PcdItem[0]\r
3685 break\r
3686 for PatchPcd in PatchList:\r
3687 if TokenCName == PatchPcd[0]:\r
3688 break\r
2a29017e 3689 else:\r
e8a47801 3690 continue\r
e8a47801 3691 PcdValue = ''\r
7ced8bb4
YZ
3692 if Pcd.DatumType == 'BOOLEAN':\r
3693 BoolValue = Pcd.DefaultValue.upper()\r
3694 if BoolValue == 'TRUE':\r
3695 Pcd.DefaultValue = '1'\r
3696 elif BoolValue == 'FALSE':\r
3697 Pcd.DefaultValue = '0'\r
3698\r
656d2539 3699 if Pcd.DatumType in TAB_PCD_NUMERIC_TYPES:\r
e8a47801 3700 HexFormat = '0x%02x'\r
656d2539 3701 if Pcd.DatumType == TAB_UINT16:\r
e8a47801 3702 HexFormat = '0x%04x'\r
656d2539 3703 elif Pcd.DatumType == TAB_UINT32:\r
e8a47801 3704 HexFormat = '0x%08x'\r
656d2539 3705 elif Pcd.DatumType == TAB_UINT64:\r
e8a47801
LG
3706 HexFormat = '0x%016x'\r
3707 PcdValue = HexFormat % int(Pcd.DefaultValue, 0)\r
3708 else:\r
4231a819 3709 if Pcd.MaxDatumSize is None or Pcd.MaxDatumSize == '':\r
e8a47801 3710 EdkLogger.error("build", AUTOGEN_ERROR,\r
2a29017e 3711 "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd.TokenSpaceGuidCName, TokenCName)\r
e8a47801
LG
3712 )\r
3713 ArraySize = int(Pcd.MaxDatumSize, 0)\r
3714 PcdValue = Pcd.DefaultValue\r
3715 if PcdValue[0] != '{':\r
3716 Unicode = False\r
3717 if PcdValue[0] == 'L':\r
3718 Unicode = True\r
3719 PcdValue = PcdValue.lstrip('L')\r
3720 PcdValue = eval(PcdValue)\r
3721 NewValue = '{'\r
3722 for Index in range(0, len(PcdValue)):\r
3723 if Unicode:\r
3724 CharVal = ord(PcdValue[Index])\r
3725 NewValue = NewValue + '0x%02x' % (CharVal & 0x00FF) + ', ' \\r
3726 + '0x%02x' % (CharVal >> 8) + ', '\r
3727 else:\r
3728 NewValue = NewValue + '0x%02x' % (ord(PcdValue[Index]) % 0x100) + ', '\r
3729 Padding = '0x00, '\r
3730 if Unicode:\r
3731 Padding = Padding * 2\r
3732 ArraySize = ArraySize / 2\r
3733 if ArraySize < (len(PcdValue) + 1):\r
c33081c9
YZ
3734 if Pcd.MaxSizeUserSet:\r
3735 EdkLogger.error("build", AUTOGEN_ERROR,\r
2a29017e 3736 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd.TokenSpaceGuidCName, TokenCName)\r
e8a47801 3737 )\r
c33081c9
YZ
3738 else:\r
3739 ArraySize = len(PcdValue) + 1\r
e8a47801
LG
3740 if ArraySize > len(PcdValue) + 1:\r
3741 NewValue = NewValue + Padding * (ArraySize - len(PcdValue) - 1)\r
3742 PcdValue = NewValue + Padding.strip().rstrip(',') + '}'\r
3743 elif len(PcdValue.split(',')) <= ArraySize:\r
3744 PcdValue = PcdValue.rstrip('}') + ', 0x00' * (ArraySize - len(PcdValue.split(',')))\r
3745 PcdValue += '}'\r
3746 else:\r
c33081c9
YZ
3747 if Pcd.MaxSizeUserSet:\r
3748 EdkLogger.error("build", AUTOGEN_ERROR,\r
2a29017e 3749 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd.TokenSpaceGuidCName, TokenCName)\r
e8a47801 3750 )\r
c33081c9
YZ
3751 else:\r
3752 ArraySize = len(PcdValue) + 1\r
e8a47801 3753 PcdItem = '%s.%s|%s|0x%X' % \\r
2a29017e 3754 (Pcd.TokenSpaceGuidCName, TokenCName, PcdValue, PatchPcd[1])\r
e8a47801
LG
3755 PcdComments = ''\r
3756 if (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in self._PcdComments:\r
3757 PcdComments = '\n '.join(self._PcdComments[Pcd.TokenSpaceGuidCName, Pcd.TokenCName])\r
3758 if PcdComments:\r
3759 PcdItem = PcdComments + '\n ' + PcdItem\r
3760 AsBuiltInfDict['patchablepcd_item'].append(PcdItem)\r
97fa0ee9 3761\r
97fa0ee9 3762 for Pcd in Pcds + VfrPcds:\r
e8a47801
LG
3763 PcdCommentList = []\r
3764 HiiInfo = ''\r
2a29017e
YZ
3765 TokenCName = Pcd.TokenCName\r
3766 for PcdItem in GlobalData.MixedPcd:\r
3767 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:\r
3768 TokenCName = PcdItem[0]\r
3769 break\r
e8a47801
LG
3770 if Pcd.Type == TAB_PCDS_DYNAMIC_EX_HII:\r
3771 for SkuName in Pcd.SkuInfoList:\r
3772 SkuInfo = Pcd.SkuInfoList[SkuName]\r
3773 HiiInfo = '## %s|%s|%s' % (SkuInfo.VariableName, SkuInfo.VariableGuid, SkuInfo.VariableOffset)\r
3774 break\r
3775 if (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in self._PcdComments:\r
3776 PcdCommentList = self._PcdComments[Pcd.TokenSpaceGuidCName, Pcd.TokenCName][:]\r
3777 if HiiInfo:\r
3778 UsageIndex = -1\r
97fa0ee9 3779 UsageStr = ''\r
e8a47801
LG
3780 for Index, Comment in enumerate(PcdCommentList):\r
3781 for Usage in UsageList:\r
3782 if Comment.find(Usage) != -1:\r
97fa0ee9 3783 UsageStr = Usage\r
e8a47801
LG
3784 UsageIndex = Index\r
3785 break\r
3786 if UsageIndex != -1:\r
f7496d71 3787 PcdCommentList[UsageIndex] = '## %s %s %s' % (UsageStr, HiiInfo, PcdCommentList[UsageIndex].replace(UsageStr, ''))\r
e8a47801 3788 else:\r
97fa0ee9 3789 PcdCommentList.append('## UNDEFINED ' + HiiInfo)\r
e8a47801 3790 PcdComments = '\n '.join(PcdCommentList)\r
2a29017e 3791 PcdEntry = Pcd.TokenSpaceGuidCName + '.' + TokenCName\r
e8a47801
LG
3792 if PcdComments:\r
3793 PcdEntry = PcdComments + '\n ' + PcdEntry\r
caf74495 3794 AsBuiltInfDict['pcd_item'].append(PcdEntry)\r
da92f276 3795 for Item in self.BuildOption:\r
481252bb 3796 if 'FLAGS' in self.BuildOption[Item]:\r
caf74495 3797 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()))\r
97fa0ee9
YL
3798\r
3799 # Generated LibraryClasses section in comments.\r
3800 for Library in self.LibraryAutoGenList:\r
caf74495 3801 AsBuiltInfDict['libraryclasses_item'].append(Library.MetaFile.File.replace('\\', '/'))\r
f7496d71 3802\r
dfa41b4a
YZ
3803 # Generated UserExtensions TianoCore section.\r
3804 # All tianocore user extensions are copied.\r
3805 UserExtStr = ''\r
3806 for TianoCore in self._GetTianoCoreUserExtensionList():\r
3807 UserExtStr += '\n'.join(TianoCore)\r
3808 ExtensionFile = os.path.join(self.MetaFile.Dir, TianoCore[1])\r
3809 if os.path.isfile(ExtensionFile):\r
3810 shutil.copy2(ExtensionFile, self.OutputDir)\r
3811 AsBuiltInfDict['userextension_tianocore_item'] = UserExtStr\r
3812\r
97fa0ee9 3813 # Generated depex expression section in comments.\r
97fa0ee9 3814 DepexExpresion = self._GetDepexExpresionString()\r
caf74495 3815 AsBuiltInfDict['depexsection_item'] = DepexExpresion if DepexExpresion else ''\r
f7496d71 3816\r
da92f276
LG
3817 AsBuiltInf = TemplateString()\r
3818 AsBuiltInf.Append(gAsBuiltInfHeaderString.Replace(AsBuiltInfDict))\r
f7496d71 3819\r
da92f276 3820 SaveFileOnChange(os.path.join(self.OutputDir, self.Name + '.inf'), str(AsBuiltInf), False)\r
f7496d71 3821\r
da92f276 3822 self.IsAsBuiltInfCreated = True\r
36d083ef
YZ
3823 if GlobalData.gBinCacheDest:\r
3824 self.CopyModuleToCache()\r
3825\r
3826 def CopyModuleToCache(self):\r
3827 FileDir = path.join(GlobalData.gBinCacheDest, self.Arch, self.SourceDir, self.MetaFile.BaseName)\r
3828 CreateDirectory (FileDir)\r
3829 HashFile = path.join(self.BuildDir, self.Name + '.hash')\r
3830 ModuleFile = path.join(self.OutputDir, self.Name + '.inf')\r
3831 if os.path.exists(HashFile):\r
3832 shutil.copy2(HashFile, FileDir)\r
3833 if os.path.exists(ModuleFile):\r
3834 shutil.copy2(ModuleFile, FileDir)\r
83397f95 3835 if not self.OutputFile:\r
e6c62ab7 3836 Ma = self.BuildDatabase[PathClass(ModuleFile), self.Arch, self.BuildTarget, self.ToolChain]\r
83397f95 3837 self.OutputFile = Ma.Binaries\r
36d083ef
YZ
3838 if self.OutputFile:\r
3839 for File in self.OutputFile:\r
83397f95 3840 File = str(File)\r
36d083ef
YZ
3841 if not os.path.isabs(File):\r
3842 File = os.path.join(self.OutputDir, File)\r
3843 if os.path.exists(File):\r
3844 shutil.copy2(File, FileDir)\r
3845\r
3846 def AttemptModuleCacheCopy(self):\r
3847 if self.IsBinaryModule:\r
3848 return False\r
3849 FileDir = path.join(GlobalData.gBinCacheSource, self.Arch, self.SourceDir, self.MetaFile.BaseName)\r
3850 HashFile = path.join(FileDir, self.Name + '.hash')\r
3851 if os.path.exists(HashFile):\r
3852 f = open(HashFile, 'r')\r
3853 CacheHash = f.read()\r
3854 f.close()\r
3855 if GlobalData.gModuleHash[self.Arch][self.Name]:\r
3856 if CacheHash == GlobalData.gModuleHash[self.Arch][self.Name]:\r
3857 for root, dir, files in os.walk(FileDir):\r
3858 for f in files:\r
3859 if self.Name + '.hash' in f:\r
3860 shutil.copy2(HashFile, self.BuildDir)\r
3861 else:\r
3862 File = path.join(root, f)\r
3863 shutil.copy2(File, self.OutputDir)\r
3864 if self.Name == "PcdPeim" or self.Name == "PcdDxe":\r
3865 CreatePcdDatabaseCode(self, TemplateString(), TemplateString())\r
3866 return True\r
3867 return False\r
3868\r
52302d4d
LG
3869 ## Create makefile for the module and its dependent libraries\r
3870 #\r
3871 # @param CreateLibraryMakeFile Flag indicating if or not the makefiles of\r
3872 # dependent libraries will be created\r
3873 #\r
830bf22f 3874 @cached_class_function\r
37de70b7 3875 def CreateMakeFile(self, CreateLibraryMakeFile=True, GenFfsList = []):\r
830bf22f
JC
3876 # nest this function inside it's only caller.\r
3877 def CreateTimeStamp():\r
3878 FileSet = {self.MetaFile.Path}\r
3879\r
3880 for SourceFile in self.Module.Sources:\r
3881 FileSet.add (SourceFile.Path)\r
3882\r
3883 for Lib in self.DependentLibraryList:\r
3884 FileSet.add (Lib.MetaFile.Path)\r
3885\r
3886 for f in self.AutoGenDepSet:\r
3887 FileSet.add (f.Path)\r
3888\r
3889 if os.path.exists (self.TimeStampPath):\r
3890 os.remove (self.TimeStampPath)\r
3891 with open(self.TimeStampPath, 'w+') as file:\r
3892 for f in FileSet:\r
3893 print(f, file=file)\r
3894\r
fae62ff2 3895 # Ignore generating makefile when it is a binary module\r
a0a2cd1e
FB
3896 if self.IsBinaryModule:\r
3897 return\r
fae62ff2 3898\r
37de70b7 3899 self.GenFfsList = GenFfsList\r
52302d4d
LG
3900 if not self.IsLibrary and CreateLibraryMakeFile:\r
3901 for LibraryAutoGen in self.LibraryAutoGenList:\r
3902 LibraryAutoGen.CreateMakeFile()\r
3903\r
36513f3a
YZ
3904 if self.CanSkip():\r
3905 return\r
3906\r
52302d4d
LG
3907 if len(self.CustomMakefile) == 0:\r
3908 Makefile = GenMake.ModuleMakefile(self)\r
3909 else:\r
3910 Makefile = GenMake.CustomMakefile(self)\r
3911 if Makefile.Generate():\r
3912 EdkLogger.debug(EdkLogger.DEBUG_9, "Generated makefile for module %s [%s]" %\r
3913 (self.Name, self.Arch))\r
3914 else:\r
3915 EdkLogger.debug(EdkLogger.DEBUG_9, "Skipped the generation of makefile for module %s [%s]" %\r
3916 (self.Name, self.Arch))\r
3917\r
830bf22f 3918 CreateTimeStamp()\r
52302d4d 3919\r
a0a2cd1e
FB
3920 def CopyBinaryFiles(self):\r
3921 for File in self.Module.Binaries:\r
3922 SrcPath = File.Path\r
ccaa7754 3923 DstPath = os.path.join(self.OutputDir, os.path.basename(SrcPath))\r
a0a2cd1e 3924 CopyLongFilePath(SrcPath, DstPath)\r
52302d4d
LG
3925 ## Create autogen code for the module and its dependent libraries\r
3926 #\r
3927 # @param CreateLibraryCodeFile Flag indicating if or not the code of\r
3928 # dependent libraries will be created\r
3929 #\r
3930 def CreateCodeFile(self, CreateLibraryCodeFile=True):\r
3931 if self.IsCodeFileCreated:\r
3932 return\r
3933\r
e8a47801
LG
3934 # Need to generate PcdDatabase even PcdDriver is binarymodule\r
3935 if self.IsBinaryModule and self.PcdIsDriver != '':\r
3936 CreatePcdDatabaseCode(self, TemplateString(), TemplateString())\r
3937 return\r
a0a2cd1e 3938 if self.IsBinaryModule:\r
49d9b71d
HC
3939 if self.IsLibrary:\r
3940 self.CopyBinaryFiles()\r
a0a2cd1e 3941 return\r
e8a47801 3942\r
52302d4d
LG
3943 if not self.IsLibrary and CreateLibraryCodeFile:\r
3944 for LibraryAutoGen in self.LibraryAutoGenList:\r
3945 LibraryAutoGen.CreateCodeFile()\r
3946\r
36513f3a
YZ
3947 if self.CanSkip():\r
3948 return\r
3949\r
52302d4d
LG
3950 AutoGenList = []\r
3951 IgoredAutoGenList = []\r
3952\r
3953 for File in self.AutoGenFileList:\r
3954 if GenC.Generate(File.Path, self.AutoGenFileList[File], File.IsBinary):\r
b36d134f 3955 #Ignore Edk AutoGen.c\r
52302d4d
LG
3956 if self.AutoGenVersion < 0x00010005 and File.Name == 'AutoGen.c':\r
3957 continue\r
3958\r
3959 AutoGenList.append(str(File))\r
3960 else:\r
3961 IgoredAutoGenList.append(str(File))\r
3962\r
3963 # Skip the following code for EDK I inf\r
3964 if self.AutoGenVersion < 0x00010005:\r
3965 return\r
3966\r
3967 for ModuleType in self.DepexList:\r
8bb63e37
CJ
3968 # Ignore empty [depex] section or [depex] section for SUP_MODULE_USER_DEFINED module\r
3969 if len(self.DepexList[ModuleType]) == 0 or ModuleType == SUP_MODULE_USER_DEFINED:\r
52302d4d 3970 continue\r
40d841f6 3971\r
52302d4d
LG
3972 Dpx = GenDepex.DependencyExpression(self.DepexList[ModuleType], ModuleType, True)\r
3973 DpxFile = gAutoGenDepexFileName % {"module_name" : self.Name}\r
3974\r
87d2afd0 3975 if len(Dpx.PostfixNotation) != 0:\r
0d2711a6 3976 self.DepexGenerated = True\r
da92f276 3977\r
52302d4d
LG
3978 if Dpx.Generate(path.join(self.OutputDir, DpxFile)):\r
3979 AutoGenList.append(str(DpxFile))\r
3980 else:\r
3981 IgoredAutoGenList.append(str(DpxFile))\r
3982\r
3983 if IgoredAutoGenList == []:\r
3984 EdkLogger.debug(EdkLogger.DEBUG_9, "Generated [%s] files for module %s [%s]" %\r
3985 (" ".join(AutoGenList), self.Name, self.Arch))\r
3986 elif AutoGenList == []:\r
3987 EdkLogger.debug(EdkLogger.DEBUG_9, "Skipped the generation of [%s] files for module %s [%s]" %\r
3988 (" ".join(IgoredAutoGenList), self.Name, self.Arch))\r
3989 else:\r
3990 EdkLogger.debug(EdkLogger.DEBUG_9, "Generated [%s] (skipped %s) files for module %s [%s]" %\r
3991 (" ".join(AutoGenList), " ".join(IgoredAutoGenList), self.Name, self.Arch))\r
3992\r
3993 self.IsCodeFileCreated = True\r
3994 return AutoGenList\r
3995\r
3996 ## Summarize the ModuleAutoGen objects of all libraries used by this module\r
b23414f6
JC
3997 @cached_property\r
3998 def LibraryAutoGenList(self):\r
3999 RetVal = []\r
4000 for Library in self.DependentLibraryList:\r
4001 La = ModuleAutoGen(\r
52302d4d
LG
4002 self.Workspace,\r
4003 Library.MetaFile,\r
4004 self.BuildTarget,\r
4005 self.ToolChain,\r
4006 self.Arch,\r
4007 self.PlatformInfo.MetaFile\r
4008 )\r
b23414f6
JC
4009 if La not in RetVal:\r
4010 RetVal.append(La)\r
4011 for Lib in La.CodaTargetList:\r
4012 self._ApplyBuildRule(Lib.Target, TAB_UNKNOWN_FILE)\r
4013 return RetVal\r
52302d4d 4014\r
36d083ef
YZ
4015 def GenModuleHash(self):\r
4016 if self.Arch not in GlobalData.gModuleHash:\r
4017 GlobalData.gModuleHash[self.Arch] = {}\r
4018 m = hashlib.md5()\r
4019 # Add Platform level hash\r
86e6cf98 4020 m.update(GlobalData.gPlatformHash.encode('utf-8'))\r
36d083ef
YZ
4021 # Add Package level hash\r
4022 if self.DependentPackageList:\r
3f34e36d 4023 for Pkg in sorted(self.DependentPackageList, key=lambda x: x.PackageName):\r
36d083ef 4024 if Pkg.PackageName in GlobalData.gPackageHash[self.Arch]:\r
86e6cf98 4025 m.update(GlobalData.gPackageHash[self.Arch][Pkg.PackageName].encode('utf-8'))\r
36d083ef
YZ
4026\r
4027 # Add Library hash\r
4028 if self.LibraryAutoGenList:\r
3f34e36d 4029 for Lib in sorted(self.LibraryAutoGenList, key=lambda x: x.Name):\r
36d083ef
YZ
4030 if Lib.Name not in GlobalData.gModuleHash[self.Arch]:\r
4031 Lib.GenModuleHash()\r
86e6cf98 4032 m.update(GlobalData.gModuleHash[self.Arch][Lib.Name].encode('utf-8'))\r
36d083ef
YZ
4033\r
4034 # Add Module self\r
86e6cf98 4035 f = open(str(self.MetaFile), 'rb')\r
36d083ef
YZ
4036 Content = f.read()\r
4037 f.close()\r
4038 m.update(Content)\r
4039 # Add Module's source files\r
4040 if self.SourceFileList:\r
3f34e36d 4041 for File in sorted(self.SourceFileList, key=lambda x: str(x)):\r
86e6cf98 4042 f = open(str(File), 'rb')\r
36d083ef
YZ
4043 Content = f.read()\r
4044 f.close()\r
4045 m.update(Content)\r
4046\r
4047 ModuleHashFile = path.join(self.BuildDir, self.Name + ".hash")\r
4048 if self.Name not in GlobalData.gModuleHash[self.Arch]:\r
4049 GlobalData.gModuleHash[self.Arch][self.Name] = m.hexdigest()\r
4050 if GlobalData.gBinCacheSource:\r
caf74495 4051 if self.AttemptModuleCacheCopy():\r
36d083ef
YZ
4052 return False\r
4053 return SaveFileOnChange(ModuleHashFile, m.hexdigest(), True)\r
4054\r
4055 ## Decide whether we can skip the ModuleAutoGen process\r
4056 def CanSkipbyHash(self):\r
4057 if GlobalData.gUseHashCache:\r
4058 return not self.GenModuleHash()\r
18ef4e71 4059 return False\r
36d083ef 4060\r
c17956e0 4061 ## Decide whether we can skip the ModuleAutoGen process\r
36d083ef 4062 # If any source file is newer than the module than we cannot skip\r
c17956e0
DL
4063 #\r
4064 def CanSkip(self):\r
0a563f3f 4065 if self.MakeFileDir in GlobalData.gSikpAutoGenCache:\r
18ef4e71 4066 return True\r
b23414f6 4067 if not os.path.exists(self.TimeStampPath):\r
c17956e0
DL
4068 return False\r
4069 #last creation time of the module\r
b23414f6 4070 DstTimeStamp = os.stat(self.TimeStampPath)[8]\r
c17956e0
DL
4071\r
4072 SrcTimeStamp = self.Workspace._SrcTimeStamp\r
4073 if SrcTimeStamp > DstTimeStamp:\r
4074 return False\r
4075\r
b23414f6 4076 with open(self.TimeStampPath,'r') as f:\r
c17956e0
DL
4077 for source in f:\r
4078 source = source.rstrip('\n')\r
4a1167df
YZ
4079 if not os.path.exists(source):\r
4080 return False\r
c17956e0
DL
4081 if source not in ModuleAutoGen.TimeDict :\r
4082 ModuleAutoGen.TimeDict[source] = os.stat(source)[8]\r
4083 if ModuleAutoGen.TimeDict[source] > DstTimeStamp:\r
4084 return False\r
0a563f3f 4085 GlobalData.gSikpAutoGenCache.add(self.MakeFileDir)\r
c17956e0
DL
4086 return True\r
4087\r
b23414f6
JC
4088 @cached_property\r
4089 def TimeStampPath(self):\r
4090 return os.path.join(self.MakeFileDir, 'AutoGenTimeStamp')\r