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