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