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