BaseTools: Enable structure pcd in FDF file
[mirror_edk2.git] / BaseTools / Source / Python / AutoGen / AutoGen.py
1 ## @file
2 # Generate AutoGen.h, AutoGen.c and *.depex files
3 #
4 # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>
5 # Copyright (c) 2018, Hewlett Packard Enterprise Development, L.P.<BR>
6 #
7 # This program and the accompanying materials
8 # are licensed and made available under the terms and conditions of the BSD License
9 # which accompanies this distribution. The full text of the license may be found at
10 # http://opensource.org/licenses/bsd-license.php
11 #
12 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
14 #
15
16 ## Import Modules
17 #
18 from __future__ import print_function
19 import Common.LongFilePathOs as os
20 import re
21 import os.path as path
22 import copy
23 import uuid
24
25 import GenC
26 import GenMake
27 import GenDepex
28 from io import BytesIO
29
30 from StrGather import *
31 from BuildEngine import BuildRule
32
33 from Common.LongFilePathSupport import CopyLongFilePath
34 from Common.BuildToolError import *
35 from Common.DataType import *
36 from Common.Misc import *
37 from Common.StringUtils import *
38 import Common.GlobalData as GlobalData
39 from GenFds.FdfParser import *
40 from CommonDataClass.CommonClass import SkuInfoClass
41 from Workspace.BuildClassObject import *
42 from GenPatchPcdTable.GenPatchPcdTable import parsePcdInfoFromMapFile
43 import Common.VpdInfoFile as VpdInfoFile
44 from GenPcdDb import CreatePcdDatabaseCode
45 from Workspace.MetaFileCommentParser import UsageList
46 from Workspace.WorkspaceCommon import GetModuleLibInstances
47 from Common.MultipleWorkspace import MultipleWorkspace as mws
48 import InfSectionParser
49 import datetime
50 import hashlib
51 from GenVar import VariableMgr, var_info
52 from collections import OrderedDict
53 from collections import defaultdict
54 from Workspace.WorkspaceCommon import OrderedListDict
55
56 ## Regular expression for splitting Dependency Expression string into tokens
57 gDepexTokenPattern = re.compile("(\(|\)|\w+| \S+\.inf)")
58
59 ## Regular expression for match: PCD(xxxx.yyy)
60 gPCDAsGuidPattern = re.compile(r"^PCD\(.+\..+\)$")
61
62 #
63 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT
64 # is the former use /I , the Latter used -I to specify include directories
65 #
66 gBuildOptIncludePatternMsft = re.compile(r"(?:.*?)/I[ \t]*([^ ]*)", re.MULTILINE | re.DOTALL)
67 gBuildOptIncludePatternOther = re.compile(r"(?:.*?)-I[ \t]*([^ ]*)", re.MULTILINE | re.DOTALL)
68
69 #
70 # Match name = variable
71 #
72 gEfiVarStoreNamePattern = re.compile("\s*name\s*=\s*(\w+)")
73 #
74 # The format of guid in efivarstore statement likes following and must be correct:
75 # guid = {0xA04A27f4, 0xDF00, 0x4D42, {0xB5, 0x52, 0x39, 0x51, 0x13, 0x02, 0x11, 0x3D}}
76 #
77 gEfiVarStoreGuidPattern = re.compile("\s*guid\s*=\s*({.*?{.*?}\s*})")
78
79 ## Mapping Makefile type
80 gMakeTypeMap = {"MSFT":"nmake", "GCC":"gmake"}
81
82
83 ## Build rule configuration file
84 gDefaultBuildRuleFile = 'build_rule.txt'
85
86 ## Tools definition configuration file
87 gDefaultToolsDefFile = 'tools_def.txt'
88
89 ## Build rule default version
90 AutoGenReqBuildRuleVerNum = "0.1"
91
92 ## default file name for AutoGen
93 gAutoGenCodeFileName = "AutoGen.c"
94 gAutoGenHeaderFileName = "AutoGen.h"
95 gAutoGenStringFileName = "%(module_name)sStrDefs.h"
96 gAutoGenStringFormFileName = "%(module_name)sStrDefs.hpk"
97 gAutoGenDepexFileName = "%(module_name)s.depex"
98 gAutoGenImageDefFileName = "%(module_name)sImgDefs.h"
99 gAutoGenIdfFileName = "%(module_name)sIdf.hpk"
100 gInfSpecVersion = "0x00010017"
101
102 #
103 # Template string to generic AsBuilt INF
104 #
105 gAsBuiltInfHeaderString = TemplateString("""${header_comments}
106
107 # DO NOT EDIT
108 # FILE auto-generated
109
110 [Defines]
111 INF_VERSION = ${module_inf_version}
112 BASE_NAME = ${module_name}
113 FILE_GUID = ${module_guid}
114 MODULE_TYPE = ${module_module_type}${BEGIN}
115 VERSION_STRING = ${module_version_string}${END}${BEGIN}
116 PCD_IS_DRIVER = ${pcd_is_driver_string}${END}${BEGIN}
117 UEFI_SPECIFICATION_VERSION = ${module_uefi_specification_version}${END}${BEGIN}
118 PI_SPECIFICATION_VERSION = ${module_pi_specification_version}${END}${BEGIN}
119 ENTRY_POINT = ${module_entry_point}${END}${BEGIN}
120 UNLOAD_IMAGE = ${module_unload_image}${END}${BEGIN}
121 CONSTRUCTOR = ${module_constructor}${END}${BEGIN}
122 DESTRUCTOR = ${module_destructor}${END}${BEGIN}
123 SHADOW = ${module_shadow}${END}${BEGIN}
124 PCI_VENDOR_ID = ${module_pci_vendor_id}${END}${BEGIN}
125 PCI_DEVICE_ID = ${module_pci_device_id}${END}${BEGIN}
126 PCI_CLASS_CODE = ${module_pci_class_code}${END}${BEGIN}
127 PCI_REVISION = ${module_pci_revision}${END}${BEGIN}
128 BUILD_NUMBER = ${module_build_number}${END}${BEGIN}
129 SPEC = ${module_spec}${END}${BEGIN}
130 UEFI_HII_RESOURCE_SECTION = ${module_uefi_hii_resource_section}${END}${BEGIN}
131 MODULE_UNI_FILE = ${module_uni_file}${END}
132
133 [Packages.${module_arch}]${BEGIN}
134 ${package_item}${END}
135
136 [Binaries.${module_arch}]${BEGIN}
137 ${binary_item}${END}
138
139 [PatchPcd.${module_arch}]${BEGIN}
140 ${patchablepcd_item}
141 ${END}
142
143 [Protocols.${module_arch}]${BEGIN}
144 ${protocol_item}
145 ${END}
146
147 [Ppis.${module_arch}]${BEGIN}
148 ${ppi_item}
149 ${END}
150
151 [Guids.${module_arch}]${BEGIN}
152 ${guid_item}
153 ${END}
154
155 [PcdEx.${module_arch}]${BEGIN}
156 ${pcd_item}
157 ${END}
158
159 [LibraryClasses.${module_arch}]
160 ## @LIB_INSTANCES${BEGIN}
161 # ${libraryclasses_item}${END}
162
163 ${depexsection_item}
164
165 ${userextension_tianocore_item}
166
167 ${tail_comments}
168
169 [BuildOptions.${module_arch}]
170 ## @AsBuilt${BEGIN}
171 ## ${flags_item}${END}
172 """)
173
174 ## Base class for AutoGen
175 #
176 # This class just implements the cache mechanism of AutoGen objects.
177 #
178 class AutoGen(object):
179 # database to maintain the objects in each child class
180 __ObjectCache = {} # (BuildTarget, ToolChain, ARCH, platform file): AutoGen object
181
182 ## Factory method
183 #
184 # @param Class class object of real AutoGen class
185 # (WorkspaceAutoGen, ModuleAutoGen or PlatformAutoGen)
186 # @param Workspace Workspace directory or WorkspaceAutoGen object
187 # @param MetaFile The path of meta file
188 # @param Target Build target
189 # @param Toolchain Tool chain name
190 # @param Arch Target arch
191 # @param *args The specific class related parameters
192 # @param **kwargs The specific class related dict parameters
193 #
194 def __new__(cls, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):
195 # check if the object has been created
196 Key = (Target, Toolchain, Arch, MetaFile)
197 try:
198 # if it exists, just return it directly
199 return cls.__ObjectCache[Key]
200 except:
201 # it didnt exist. create it, cache it, then return it
202 cls.__ObjectCache[Key] = super(AutoGen, cls).__new__(cls)
203 return cls.__ObjectCache[Key]
204
205 def __init__ (self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):
206 super(AutoGen, self).__init__(self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)
207
208 ## hash() operator
209 #
210 # The file path of platform file will be used to represent hash value of this object
211 #
212 # @retval int Hash value of the file path of platform file
213 #
214 def __hash__(self):
215 return hash(self.MetaFile)
216
217 ## str() operator
218 #
219 # The file path of platform file will be used to represent this object
220 #
221 # @retval string String of platform file path
222 #
223 def __str__(self):
224 return str(self.MetaFile)
225
226 ## "==" operator
227 def __eq__(self, Other):
228 return Other and self.MetaFile == Other
229
230 ## Workspace AutoGen class
231 #
232 # This class is used mainly to control the whole platform build for different
233 # architecture. This class will generate top level makefile.
234 #
235 class WorkspaceAutoGen(AutoGen):
236 # call super().__init__ then call the worker function with different parameter count
237 def __init__(self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):
238 try:
239 self._Init
240 except:
241 super(WorkspaceAutoGen, self).__init__(Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)
242 self._InitWorker(Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)
243 self._Init = True
244
245 ## Initialize WorkspaceAutoGen
246 #
247 # @param WorkspaceDir Root directory of workspace
248 # @param ActivePlatform Meta-file of active platform
249 # @param Target Build target
250 # @param Toolchain Tool chain name
251 # @param ArchList List of architecture of current build
252 # @param MetaFileDb Database containing meta-files
253 # @param BuildConfig Configuration of build
254 # @param ToolDefinition Tool chain definitions
255 # @param FlashDefinitionFile File of flash definition
256 # @param Fds FD list to be generated
257 # @param Fvs FV list to be generated
258 # @param Caps Capsule list to be generated
259 # @param SkuId SKU id from command line
260 #
261 def _InitWorker(self, WorkspaceDir, ActivePlatform, Target, Toolchain, ArchList, MetaFileDb,
262 BuildConfig, ToolDefinition, FlashDefinitionFile='', Fds=None, Fvs=None, Caps=None, SkuId='', UniFlag=None,
263 Progress=None, BuildModule=None):
264 self.BuildDatabase = MetaFileDb
265 self.MetaFile = ActivePlatform
266 self.WorkspaceDir = WorkspaceDir
267 self.Platform = self.BuildDatabase[self.MetaFile, TAB_ARCH_COMMON, Target, Toolchain]
268 GlobalData.gActivePlatform = self.Platform
269 self.BuildTarget = Target
270 self.ToolChain = Toolchain
271 self.ArchList = ArchList
272 self.SkuId = SkuId
273 self.UniFlag = UniFlag
274
275 self.TargetTxt = BuildConfig
276 self.ToolDef = ToolDefinition
277 self.FdfFile = FlashDefinitionFile
278 self.FdTargetList = Fds if Fds else []
279 self.FvTargetList = Fvs if Fvs else []
280 self.CapTargetList = Caps if Caps else []
281 self.AutoGenObjectList = []
282 self._BuildDir = None
283 self._FvDir = None
284 self._MakeFileDir = None
285 self._BuildCommand = None
286 self._GuidDict = {}
287
288 # there's many relative directory operations, so ...
289 os.chdir(self.WorkspaceDir)
290
291 #
292 # Merge Arch
293 #
294 if not self.ArchList:
295 ArchList = set(self.Platform.SupArchList)
296 else:
297 ArchList = set(self.ArchList) & set(self.Platform.SupArchList)
298 if not ArchList:
299 EdkLogger.error("build", PARAMETER_INVALID,
300 ExtraData = "Invalid ARCH specified. [Valid ARCH: %s]" % (" ".join(self.Platform.SupArchList)))
301 elif self.ArchList and len(ArchList) != len(self.ArchList):
302 SkippedArchList = set(self.ArchList).symmetric_difference(set(self.Platform.SupArchList))
303 EdkLogger.verbose("\nArch [%s] is ignored because the platform supports [%s] only!"
304 % (" ".join(SkippedArchList), " ".join(self.Platform.SupArchList)))
305 self.ArchList = tuple(ArchList)
306
307 # Validate build target
308 if self.BuildTarget not in self.Platform.BuildTargets:
309 EdkLogger.error("build", PARAMETER_INVALID,
310 ExtraData="Build target [%s] is not supported by the platform. [Valid target: %s]"
311 % (self.BuildTarget, " ".join(self.Platform.BuildTargets)))
312
313
314 # parse FDF file to get PCDs in it, if any
315 if not self.FdfFile:
316 self.FdfFile = self.Platform.FlashDefinition
317
318 EdkLogger.info("")
319 if self.ArchList:
320 EdkLogger.info('%-16s = %s' % ("Architecture(s)", ' '.join(self.ArchList)))
321 EdkLogger.info('%-16s = %s' % ("Build target", self.BuildTarget))
322 EdkLogger.info('%-16s = %s' % ("Toolchain", self.ToolChain))
323
324 EdkLogger.info('\n%-24s = %s' % ("Active Platform", self.Platform))
325 if BuildModule:
326 EdkLogger.info('%-24s = %s' % ("Active Module", BuildModule))
327
328 if self.FdfFile:
329 EdkLogger.info('%-24s = %s' % ("Flash Image Definition", self.FdfFile))
330
331 EdkLogger.verbose("\nFLASH_DEFINITION = %s" % self.FdfFile)
332
333 if Progress:
334 Progress.Start("\nProcessing meta-data")
335
336 if self.FdfFile:
337 #
338 # Mark now build in AutoGen Phase
339 #
340 GlobalData.gAutoGenPhase = True
341 Fdf = FdfParser(self.FdfFile.Path)
342 Fdf.ParseFile()
343 GlobalData.gFdfParser = Fdf
344 GlobalData.gAutoGenPhase = False
345 PcdSet = Fdf.Profile.PcdDict
346 if Fdf.CurrentFdName and Fdf.CurrentFdName in Fdf.Profile.FdDict:
347 FdDict = Fdf.Profile.FdDict[Fdf.CurrentFdName]
348 for FdRegion in FdDict.RegionList:
349 if str(FdRegion.RegionType) is 'FILE' and self.Platform.VpdToolGuid in str(FdRegion.RegionDataList):
350 if int(FdRegion.Offset) % 8 != 0:
351 EdkLogger.error("build", FORMAT_INVALID, 'The VPD Base Address %s must be 8-byte aligned.' % (FdRegion.Offset))
352 ModuleList = Fdf.Profile.InfList
353 self.FdfProfile = Fdf.Profile
354 for fvname in self.FvTargetList:
355 if fvname.upper() not in self.FdfProfile.FvDict:
356 EdkLogger.error("build", OPTION_VALUE_INVALID,
357 "No such an FV in FDF file: %s" % fvname)
358
359 # In DSC file may use FILE_GUID to override the module, then in the Platform.Modules use FILE_GUIDmodule.inf as key,
360 # but the path (self.MetaFile.Path) is the real path
361 for key in self.FdfProfile.InfDict:
362 if key == 'ArchTBD':
363 MetaFile_cache = defaultdict(set)
364 for Arch in self.ArchList:
365 Current_Platform_cache = self.BuildDatabase[self.MetaFile, Arch, Target, Toolchain]
366 for Pkey in Current_Platform_cache.Modules:
367 MetaFile_cache[Arch].add(Current_Platform_cache.Modules[Pkey].MetaFile)
368 for Inf in self.FdfProfile.InfDict[key]:
369 ModuleFile = PathClass(NormPath(Inf), GlobalData.gWorkspace, Arch)
370 for Arch in self.ArchList:
371 if ModuleFile in MetaFile_cache[Arch]:
372 break
373 else:
374 ModuleData = self.BuildDatabase[ModuleFile, Arch, Target, Toolchain]
375 if not ModuleData.IsBinaryModule:
376 EdkLogger.error('build', PARSER_ERROR, "Module %s NOT found in DSC file; Is it really a binary module?" % ModuleFile)
377
378 else:
379 for Arch in self.ArchList:
380 if Arch == key:
381 Platform = self.BuildDatabase[self.MetaFile, Arch, Target, Toolchain]
382 MetaFileList = set()
383 for Pkey in Platform.Modules:
384 MetaFileList.add(Platform.Modules[Pkey].MetaFile)
385 for Inf in self.FdfProfile.InfDict[key]:
386 ModuleFile = PathClass(NormPath(Inf), GlobalData.gWorkspace, Arch)
387 if ModuleFile in MetaFileList:
388 continue
389 ModuleData = self.BuildDatabase[ModuleFile, Arch, Target, Toolchain]
390 if not ModuleData.IsBinaryModule:
391 EdkLogger.error('build', PARSER_ERROR, "Module %s NOT found in DSC file; Is it really a binary module?" % ModuleFile)
392
393 else:
394 PcdSet = {}
395 ModuleList = []
396 self.FdfProfile = None
397 if self.FdTargetList:
398 EdkLogger.info("No flash definition file found. FD [%s] will be ignored." % " ".join(self.FdTargetList))
399 self.FdTargetList = []
400 if self.FvTargetList:
401 EdkLogger.info("No flash definition file found. FV [%s] will be ignored." % " ".join(self.FvTargetList))
402 self.FvTargetList = []
403 if self.CapTargetList:
404 EdkLogger.info("No flash definition file found. Capsule [%s] will be ignored." % " ".join(self.CapTargetList))
405 self.CapTargetList = []
406
407 # apply SKU and inject PCDs from Flash Definition file
408 for Arch in self.ArchList:
409 Platform = self.BuildDatabase[self.MetaFile, Arch, Target, Toolchain]
410 PlatformPcds = Platform.Pcds
411 self._GuidDict = Platform._GuidDict
412 SourcePcdDict = {TAB_PCDS_DYNAMIC_EX:set(), TAB_PCDS_PATCHABLE_IN_MODULE:set(),TAB_PCDS_DYNAMIC:set(),TAB_PCDS_FIXED_AT_BUILD:set()}
413 BinaryPcdDict = {TAB_PCDS_DYNAMIC_EX:set(), TAB_PCDS_PATCHABLE_IN_MODULE:set()}
414 SourcePcdDict_Keys = SourcePcdDict.keys()
415 BinaryPcdDict_Keys = BinaryPcdDict.keys()
416
417 # generate the SourcePcdDict and BinaryPcdDict
418 PGen = PlatformAutoGen(self, self.MetaFile, Target, Toolchain, Arch)
419 for BuildData in PGen.BuildDatabase._CACHE_.values():
420 if BuildData.Arch != Arch:
421 continue
422 if BuildData.MetaFile.Ext == '.inf':
423 for key in BuildData.Pcds:
424 if BuildData.Pcds[key].Pending:
425 if key in Platform.Pcds:
426 PcdInPlatform = Platform.Pcds[key]
427 if PcdInPlatform.Type:
428 BuildData.Pcds[key].Type = PcdInPlatform.Type
429 BuildData.Pcds[key].Pending = False
430
431 if BuildData.MetaFile in Platform.Modules:
432 PlatformModule = Platform.Modules[str(BuildData.MetaFile)]
433 if key in PlatformModule.Pcds:
434 PcdInPlatform = PlatformModule.Pcds[key]
435 if PcdInPlatform.Type:
436 BuildData.Pcds[key].Type = PcdInPlatform.Type
437 BuildData.Pcds[key].Pending = False
438 else:
439 #Pcd used in Library, Pcd Type from reference module if Pcd Type is Pending
440 if BuildData.Pcds[key].Pending:
441 MGen = ModuleAutoGen(self, BuildData.MetaFile, Target, Toolchain, Arch, self.MetaFile)
442 if MGen and MGen.IsLibrary:
443 if MGen in PGen.LibraryAutoGenList:
444 ReferenceModules = MGen._ReferenceModules
445 for ReferenceModule in ReferenceModules:
446 if ReferenceModule.MetaFile in Platform.Modules:
447 RefPlatformModule = Platform.Modules[str(ReferenceModule.MetaFile)]
448 if key in RefPlatformModule.Pcds:
449 PcdInReferenceModule = RefPlatformModule.Pcds[key]
450 if PcdInReferenceModule.Type:
451 BuildData.Pcds[key].Type = PcdInReferenceModule.Type
452 BuildData.Pcds[key].Pending = False
453 break
454
455 if TAB_PCDS_DYNAMIC_EX in BuildData.Pcds[key].Type:
456 if BuildData.IsBinaryModule:
457 BinaryPcdDict[TAB_PCDS_DYNAMIC_EX].add((BuildData.Pcds[key].TokenCName, BuildData.Pcds[key].TokenSpaceGuidCName))
458 else:
459 SourcePcdDict[TAB_PCDS_DYNAMIC_EX].add((BuildData.Pcds[key].TokenCName, BuildData.Pcds[key].TokenSpaceGuidCName))
460
461 elif TAB_PCDS_PATCHABLE_IN_MODULE in BuildData.Pcds[key].Type:
462 if BuildData.MetaFile.Ext == '.inf':
463 if BuildData.IsBinaryModule:
464 BinaryPcdDict[TAB_PCDS_PATCHABLE_IN_MODULE].add((BuildData.Pcds[key].TokenCName, BuildData.Pcds[key].TokenSpaceGuidCName))
465 else:
466 SourcePcdDict[TAB_PCDS_PATCHABLE_IN_MODULE].add((BuildData.Pcds[key].TokenCName, BuildData.Pcds[key].TokenSpaceGuidCName))
467
468 elif TAB_PCDS_DYNAMIC in BuildData.Pcds[key].Type:
469 SourcePcdDict[TAB_PCDS_DYNAMIC].add((BuildData.Pcds[key].TokenCName, BuildData.Pcds[key].TokenSpaceGuidCName))
470 elif TAB_PCDS_FIXED_AT_BUILD in BuildData.Pcds[key].Type:
471 SourcePcdDict[TAB_PCDS_FIXED_AT_BUILD].add((BuildData.Pcds[key].TokenCName, BuildData.Pcds[key].TokenSpaceGuidCName))
472 else:
473 pass
474 #
475 # A PCD can only use one type for all source modules
476 #
477 for i in SourcePcdDict_Keys:
478 for j in SourcePcdDict_Keys:
479 if i != j:
480 Intersections = SourcePcdDict[i].intersection(SourcePcdDict[j])
481 if len(Intersections) > 0:
482 EdkLogger.error(
483 'build',
484 FORMAT_INVALID,
485 "Building modules from source INFs, following PCD use %s and %s access method. It must be corrected to use only one access method." % (i, j),
486 ExtraData='\n\t'.join(str(P[1]+'.'+P[0]) for P in Intersections)
487 )
488
489 #
490 # intersection the BinaryPCD for Mixed PCD
491 #
492 for i in BinaryPcdDict_Keys:
493 for j in BinaryPcdDict_Keys:
494 if i != j:
495 Intersections = BinaryPcdDict[i].intersection(BinaryPcdDict[j])
496 for item in Intersections:
497 NewPcd1 = (item[0] + '_' + i, item[1])
498 NewPcd2 = (item[0] + '_' + j, item[1])
499 if item not in GlobalData.MixedPcd:
500 GlobalData.MixedPcd[item] = [NewPcd1, NewPcd2]
501 else:
502 if NewPcd1 not in GlobalData.MixedPcd[item]:
503 GlobalData.MixedPcd[item].append(NewPcd1)
504 if NewPcd2 not in GlobalData.MixedPcd[item]:
505 GlobalData.MixedPcd[item].append(NewPcd2)
506
507 #
508 # intersection the SourcePCD and BinaryPCD for Mixed PCD
509 #
510 for i in SourcePcdDict_Keys:
511 for j in BinaryPcdDict_Keys:
512 if i != j:
513 Intersections = SourcePcdDict[i].intersection(BinaryPcdDict[j])
514 for item in Intersections:
515 NewPcd1 = (item[0] + '_' + i, item[1])
516 NewPcd2 = (item[0] + '_' + j, item[1])
517 if item not in GlobalData.MixedPcd:
518 GlobalData.MixedPcd[item] = [NewPcd1, NewPcd2]
519 else:
520 if NewPcd1 not in GlobalData.MixedPcd[item]:
521 GlobalData.MixedPcd[item].append(NewPcd1)
522 if NewPcd2 not in GlobalData.MixedPcd[item]:
523 GlobalData.MixedPcd[item].append(NewPcd2)
524
525 for BuildData in PGen.BuildDatabase._CACHE_.values():
526 if BuildData.Arch != Arch:
527 continue
528 for key in BuildData.Pcds:
529 for SinglePcd in GlobalData.MixedPcd:
530 if (BuildData.Pcds[key].TokenCName, BuildData.Pcds[key].TokenSpaceGuidCName) == SinglePcd:
531 for item in GlobalData.MixedPcd[SinglePcd]:
532 Pcd_Type = item[0].split('_')[-1]
533 if (Pcd_Type == BuildData.Pcds[key].Type) or (Pcd_Type == TAB_PCDS_DYNAMIC_EX and BuildData.Pcds[key].Type in PCD_DYNAMIC_EX_TYPE_SET) or \
534 (Pcd_Type == TAB_PCDS_DYNAMIC and BuildData.Pcds[key].Type in PCD_DYNAMIC_TYPE_SET):
535 Value = BuildData.Pcds[key]
536 Value.TokenCName = BuildData.Pcds[key].TokenCName + '_' + Pcd_Type
537 if len(key) == 2:
538 newkey = (Value.TokenCName, key[1])
539 elif len(key) == 3:
540 newkey = (Value.TokenCName, key[1], key[2])
541 del BuildData.Pcds[key]
542 BuildData.Pcds[newkey] = Value
543 break
544 break
545
546 # handle the mixed pcd in FDF file
547 for key in PcdSet:
548 if key in GlobalData.MixedPcd:
549 Value = PcdSet[key]
550 del PcdSet[key]
551 for item in GlobalData.MixedPcd[key]:
552 PcdSet[item] = Value
553
554 #Collect package set information from INF of FDF
555 PkgSet = set()
556 for Inf in ModuleList:
557 ModuleFile = PathClass(NormPath(Inf), GlobalData.gWorkspace, Arch)
558 if ModuleFile in Platform.Modules:
559 continue
560 ModuleData = self.BuildDatabase[ModuleFile, Arch, Target, Toolchain]
561 PkgSet.update(ModuleData.Packages)
562 Pkgs = list(PkgSet) + list(PGen.PackageList)
563 DecPcds = set()
564 DecPcdsKey = set()
565 for Pkg in Pkgs:
566 for Pcd in Pkg.Pcds:
567 DecPcds.add((Pcd[0], Pcd[1]))
568 DecPcdsKey.add((Pcd[0], Pcd[1], Pcd[2]))
569
570 Platform.SkuName = self.SkuId
571 for Name, Guid,Fileds in PcdSet:
572 if (Name, Guid) not in DecPcds:
573 EdkLogger.error(
574 'build',
575 PARSER_ERROR,
576 "PCD (%s.%s) used in FDF is not declared in DEC files." % (Guid, Name),
577 File = self.FdfProfile.PcdFileLineDict[Name, Guid][0],
578 Line = self.FdfProfile.PcdFileLineDict[Name, Guid][1]
579 )
580 else:
581 # Check whether Dynamic or DynamicEx PCD used in FDF file. If used, build break and give a error message.
582 if (Name, Guid, TAB_PCDS_FIXED_AT_BUILD) in DecPcdsKey \
583 or (Name, Guid, TAB_PCDS_PATCHABLE_IN_MODULE) in DecPcdsKey \
584 or (Name, Guid, TAB_PCDS_FEATURE_FLAG) in DecPcdsKey:
585 continue
586 elif (Name, Guid, TAB_PCDS_DYNAMIC) in DecPcdsKey or (Name, Guid, TAB_PCDS_DYNAMIC_EX) in DecPcdsKey:
587 EdkLogger.error(
588 'build',
589 PARSER_ERROR,
590 "Using Dynamic or DynamicEx type of PCD [%s.%s] in FDF file is not allowed." % (Guid, Name),
591 File = self.FdfProfile.PcdFileLineDict[Name, Guid][0],
592 Line = self.FdfProfile.PcdFileLineDict[Name, Guid][1]
593 )
594
595 Pa = PlatformAutoGen(self, self.MetaFile, Target, Toolchain, Arch)
596 #
597 # Explicitly collect platform's dynamic PCDs
598 #
599 Pa.CollectPlatformDynamicPcds()
600 Pa.CollectFixedAtBuildPcds()
601 self.AutoGenObjectList.append(Pa)
602
603 #
604 # Generate Package level hash value
605 #
606 GlobalData.gPackageHash[Arch] = {}
607 if GlobalData.gUseHashCache:
608 for Pkg in Pkgs:
609 self._GenPkgLevelHash(Pkg)
610
611 #
612 # Check PCDs token value conflict in each DEC file.
613 #
614 self._CheckAllPcdsTokenValueConflict()
615
616 #
617 # Check PCD type and definition between DSC and DEC
618 #
619 self._CheckPcdDefineAndType()
620
621 # if self.FdfFile:
622 # self._CheckDuplicateInFV(Fdf)
623
624 #
625 # Create BuildOptions Macro & PCD metafile, also add the Active Platform and FDF file.
626 #
627 content = 'gCommandLineDefines: '
628 content += str(GlobalData.gCommandLineDefines)
629 content += os.linesep
630 content += 'BuildOptionPcd: '
631 content += str(GlobalData.BuildOptionPcd)
632 content += os.linesep
633 content += 'Active Platform: '
634 content += str(self.Platform)
635 content += os.linesep
636 if self.FdfFile:
637 content += 'Flash Image Definition: '
638 content += str(self.FdfFile)
639 content += os.linesep
640 SaveFileOnChange(os.path.join(self.BuildDir, 'BuildOptions'), content, False)
641
642 #
643 # Create PcdToken Number file for Dynamic/DynamicEx Pcd.
644 #
645 PcdTokenNumber = 'PcdTokenNumber: '
646 if Pa.PcdTokenNumber:
647 if Pa.DynamicPcdList:
648 for Pcd in Pa.DynamicPcdList:
649 PcdTokenNumber += os.linesep
650 PcdTokenNumber += str((Pcd.TokenCName, Pcd.TokenSpaceGuidCName))
651 PcdTokenNumber += ' : '
652 PcdTokenNumber += str(Pa.PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName])
653 SaveFileOnChange(os.path.join(self.BuildDir, 'PcdTokenNumber'), PcdTokenNumber, False)
654
655 #
656 # Get set of workspace metafiles
657 #
658 AllWorkSpaceMetaFiles = self._GetMetaFiles(Target, Toolchain, Arch)
659
660 #
661 # Retrieve latest modified time of all metafiles
662 #
663 SrcTimeStamp = 0
664 for f in AllWorkSpaceMetaFiles:
665 if os.stat(f)[8] > SrcTimeStamp:
666 SrcTimeStamp = os.stat(f)[8]
667 self._SrcTimeStamp = SrcTimeStamp
668
669 if GlobalData.gUseHashCache:
670 m = hashlib.md5()
671 for files in AllWorkSpaceMetaFiles:
672 if files.endswith('.dec'):
673 continue
674 f = open(files, 'r')
675 Content = f.read()
676 f.close()
677 m.update(Content)
678 SaveFileOnChange(os.path.join(self.BuildDir, 'AutoGen.hash'), m.hexdigest(), True)
679 GlobalData.gPlatformHash = m.hexdigest()
680
681 #
682 # Write metafile list to build directory
683 #
684 AutoGenFilePath = os.path.join(self.BuildDir, 'AutoGen')
685 if os.path.exists (AutoGenFilePath):
686 os.remove(AutoGenFilePath)
687 if not os.path.exists(self.BuildDir):
688 os.makedirs(self.BuildDir)
689 with open(os.path.join(self.BuildDir, 'AutoGen'), 'w+') as file:
690 for f in AllWorkSpaceMetaFiles:
691 print(f, file=file)
692 return True
693
694 def _GenPkgLevelHash(self, Pkg):
695 if Pkg.PackageName in GlobalData.gPackageHash[Pkg.Arch]:
696 return
697
698 PkgDir = os.path.join(self.BuildDir, Pkg.Arch, Pkg.PackageName)
699 CreateDirectory(PkgDir)
700 HashFile = os.path.join(PkgDir, Pkg.PackageName + '.hash')
701 m = hashlib.md5()
702 # Get .dec file's hash value
703 f = open(Pkg.MetaFile.Path, 'r')
704 Content = f.read()
705 f.close()
706 m.update(Content)
707 # Get include files hash value
708 if Pkg.Includes:
709 for inc in sorted(Pkg.Includes, key=lambda x: str(x)):
710 for Root, Dirs, Files in os.walk(str(inc)):
711 for File in sorted(Files):
712 File_Path = os.path.join(Root, File)
713 f = open(File_Path, 'r')
714 Content = f.read()
715 f.close()
716 m.update(Content)
717 SaveFileOnChange(HashFile, m.hexdigest(), True)
718 GlobalData.gPackageHash[Pkg.Arch][Pkg.PackageName] = m.hexdigest()
719
720 def _GetMetaFiles(self, Target, Toolchain, Arch):
721 AllWorkSpaceMetaFiles = set()
722 #
723 # add fdf
724 #
725 if self.FdfFile:
726 AllWorkSpaceMetaFiles.add (self.FdfFile.Path)
727 for f in GlobalData.gFdfParser.GetAllIncludedFile():
728 AllWorkSpaceMetaFiles.add (f.FileName)
729 #
730 # add dsc
731 #
732 AllWorkSpaceMetaFiles.add(self.MetaFile.Path)
733
734 #
735 # add build_rule.txt & tools_def.txt
736 #
737 AllWorkSpaceMetaFiles.add(os.path.join(GlobalData.gConfDirectory, gDefaultBuildRuleFile))
738 AllWorkSpaceMetaFiles.add(os.path.join(GlobalData.gConfDirectory, gDefaultToolsDefFile))
739
740 # add BuildOption metafile
741 #
742 AllWorkSpaceMetaFiles.add(os.path.join(self.BuildDir, 'BuildOptions'))
743
744 # add PcdToken Number file for Dynamic/DynamicEx Pcd
745 #
746 AllWorkSpaceMetaFiles.add(os.path.join(self.BuildDir, 'PcdTokenNumber'))
747
748 for Arch in self.ArchList:
749 #
750 # add dec
751 #
752 for Package in PlatformAutoGen(self, self.MetaFile, Target, Toolchain, Arch).PackageList:
753 AllWorkSpaceMetaFiles.add(Package.MetaFile.Path)
754
755 #
756 # add included dsc
757 #
758 for filePath in self.BuildDatabase[self.MetaFile, Arch, Target, Toolchain]._RawData.IncludedFiles:
759 AllWorkSpaceMetaFiles.add(filePath.Path)
760
761 return AllWorkSpaceMetaFiles
762
763 ## _CheckDuplicateInFV() method
764 #
765 # Check whether there is duplicate modules/files exist in FV section.
766 # The check base on the file GUID;
767 #
768 def _CheckDuplicateInFV(self, Fdf):
769 for Fv in Fdf.Profile.FvDict:
770 _GuidDict = {}
771 for FfsFile in Fdf.Profile.FvDict[Fv].FfsList:
772 if FfsFile.InfFileName and FfsFile.NameGuid is None:
773 #
774 # Get INF file GUID
775 #
776 InfFoundFlag = False
777 for Pa in self.AutoGenObjectList:
778 if InfFoundFlag:
779 break
780 for Module in Pa.ModuleAutoGenList:
781 if path.normpath(Module.MetaFile.File) == path.normpath(FfsFile.InfFileName):
782 InfFoundFlag = True
783 if Module.Guid.upper() not in _GuidDict:
784 _GuidDict[Module.Guid.upper()] = FfsFile
785 break
786 else:
787 EdkLogger.error("build",
788 FORMAT_INVALID,
789 "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile.CurrentLineNum,
790 FfsFile.CurrentLineContent,
791 _GuidDict[Module.Guid.upper()].CurrentLineNum,
792 _GuidDict[Module.Guid.upper()].CurrentLineContent,
793 Module.Guid.upper()),
794 ExtraData=self.FdfFile)
795 #
796 # Some INF files not have entity in DSC file.
797 #
798 if not InfFoundFlag:
799 if FfsFile.InfFileName.find('$') == -1:
800 InfPath = NormPath(FfsFile.InfFileName)
801 if not os.path.exists(InfPath):
802 EdkLogger.error('build', GENFDS_ERROR, "Non-existant Module %s !" % (FfsFile.InfFileName))
803
804 PathClassObj = PathClass(FfsFile.InfFileName, self.WorkspaceDir)
805 #
806 # Here we just need to get FILE_GUID from INF file, use 'COMMON' as ARCH attribute. and use
807 # BuildObject from one of AutoGenObjectList is enough.
808 #
809 InfObj = self.AutoGenObjectList[0].BuildDatabase.WorkspaceDb.BuildObject[PathClassObj, TAB_ARCH_COMMON, self.BuildTarget, self.ToolChain]
810 if InfObj.Guid.upper() not in _GuidDict:
811 _GuidDict[InfObj.Guid.upper()] = FfsFile
812 else:
813 EdkLogger.error("build",
814 FORMAT_INVALID,
815 "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile.CurrentLineNum,
816 FfsFile.CurrentLineContent,
817 _GuidDict[InfObj.Guid.upper()].CurrentLineNum,
818 _GuidDict[InfObj.Guid.upper()].CurrentLineContent,
819 InfObj.Guid.upper()),
820 ExtraData=self.FdfFile)
821 InfFoundFlag = False
822
823 if FfsFile.NameGuid is not None:
824 #
825 # If the NameGuid reference a PCD name.
826 # The style must match: PCD(xxxx.yyy)
827 #
828 if gPCDAsGuidPattern.match(FfsFile.NameGuid):
829 #
830 # Replace the PCD value.
831 #
832 _PcdName = FfsFile.NameGuid.lstrip("PCD(").rstrip(")")
833 PcdFoundFlag = False
834 for Pa in self.AutoGenObjectList:
835 if not PcdFoundFlag:
836 for PcdItem in Pa.AllPcdList:
837 if (PcdItem.TokenSpaceGuidCName + "." + PcdItem.TokenCName) == _PcdName:
838 #
839 # First convert from CFormatGuid to GUID string
840 #
841 _PcdGuidString = GuidStructureStringToGuidString(PcdItem.DefaultValue)
842
843 if not _PcdGuidString:
844 #
845 # Then try Byte array.
846 #
847 _PcdGuidString = GuidStructureByteArrayToGuidString(PcdItem.DefaultValue)
848
849 if not _PcdGuidString:
850 #
851 # Not Byte array or CFormat GUID, raise error.
852 #
853 EdkLogger.error("build",
854 FORMAT_INVALID,
855 "The format of PCD value is incorrect. PCD: %s , Value: %s\n" % (_PcdName, PcdItem.DefaultValue),
856 ExtraData=self.FdfFile)
857
858 if _PcdGuidString.upper() not in _GuidDict:
859 _GuidDict[_PcdGuidString.upper()] = FfsFile
860 PcdFoundFlag = True
861 break
862 else:
863 EdkLogger.error("build",
864 FORMAT_INVALID,
865 "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile.CurrentLineNum,
866 FfsFile.CurrentLineContent,
867 _GuidDict[_PcdGuidString.upper()].CurrentLineNum,
868 _GuidDict[_PcdGuidString.upper()].CurrentLineContent,
869 FfsFile.NameGuid.upper()),
870 ExtraData=self.FdfFile)
871
872 if FfsFile.NameGuid.upper() not in _GuidDict:
873 _GuidDict[FfsFile.NameGuid.upper()] = FfsFile
874 else:
875 #
876 # Two raw file GUID conflict.
877 #
878 EdkLogger.error("build",
879 FORMAT_INVALID,
880 "Duplicate GUID found for these lines: Line %d: %s and Line %d: %s. GUID: %s" % (FfsFile.CurrentLineNum,
881 FfsFile.CurrentLineContent,
882 _GuidDict[FfsFile.NameGuid.upper()].CurrentLineNum,
883 _GuidDict[FfsFile.NameGuid.upper()].CurrentLineContent,
884 FfsFile.NameGuid.upper()),
885 ExtraData=self.FdfFile)
886
887
888 def _CheckPcdDefineAndType(self):
889 PcdTypeSet = {TAB_PCDS_FIXED_AT_BUILD,
890 TAB_PCDS_PATCHABLE_IN_MODULE,
891 TAB_PCDS_FEATURE_FLAG,
892 TAB_PCDS_DYNAMIC,
893 TAB_PCDS_DYNAMIC_EX}
894
895 # This dict store PCDs which are not used by any modules with specified arches
896 UnusedPcd = OrderedDict()
897 for Pa in self.AutoGenObjectList:
898 # Key of DSC's Pcds dictionary is PcdCName, TokenSpaceGuid
899 for Pcd in Pa.Platform.Pcds:
900 PcdType = Pa.Platform.Pcds[Pcd].Type
901
902 # If no PCD type, this PCD comes from FDF
903 if not PcdType:
904 continue
905
906 # Try to remove Hii and Vpd suffix
907 if PcdType.startswith(TAB_PCDS_DYNAMIC_EX):
908 PcdType = TAB_PCDS_DYNAMIC_EX
909 elif PcdType.startswith(TAB_PCDS_DYNAMIC):
910 PcdType = TAB_PCDS_DYNAMIC
911
912 for Package in Pa.PackageList:
913 # Key of DEC's Pcds dictionary is PcdCName, TokenSpaceGuid, PcdType
914 if (Pcd[0], Pcd[1], PcdType) in Package.Pcds:
915 break
916 for Type in PcdTypeSet:
917 if (Pcd[0], Pcd[1], Type) in Package.Pcds:
918 EdkLogger.error(
919 'build',
920 FORMAT_INVALID,
921 "Type [%s] of PCD [%s.%s] in DSC file doesn't match the type [%s] defined in DEC file." \
922 % (Pa.Platform.Pcds[Pcd].Type, Pcd[1], Pcd[0], Type),
923 ExtraData=None
924 )
925 return
926 else:
927 UnusedPcd.setdefault(Pcd, []).append(Pa.Arch)
928
929 for Pcd in UnusedPcd:
930 EdkLogger.warn(
931 'build',
932 "The PCD was not specified by any INF module in the platform for the given architecture.\n"
933 "\tPCD: [%s.%s]\n\tPlatform: [%s]\n\tArch: %s"
934 % (Pcd[1], Pcd[0], os.path.basename(str(self.MetaFile)), str(UnusedPcd[Pcd])),
935 ExtraData=None
936 )
937
938 def __repr__(self):
939 return "%s [%s]" % (self.MetaFile, ", ".join(self.ArchList))
940
941 ## Return the directory to store FV files
942 def _GetFvDir(self):
943 if self._FvDir is None:
944 self._FvDir = path.join(self.BuildDir, TAB_FV_DIRECTORY)
945 return self._FvDir
946
947 ## Return the directory to store all intermediate and final files built
948 def _GetBuildDir(self):
949 if self._BuildDir is None:
950 return self.AutoGenObjectList[0].BuildDir
951
952 ## Return the build output directory platform specifies
953 def _GetOutputDir(self):
954 return self.Platform.OutputDirectory
955
956 ## Return platform name
957 def _GetName(self):
958 return self.Platform.PlatformName
959
960 ## Return meta-file GUID
961 def _GetGuid(self):
962 return self.Platform.Guid
963
964 ## Return platform version
965 def _GetVersion(self):
966 return self.Platform.Version
967
968 ## Return paths of tools
969 def _GetToolDefinition(self):
970 return self.AutoGenObjectList[0].ToolDefinition
971
972 ## Return directory of platform makefile
973 #
974 # @retval string Makefile directory
975 #
976 def _GetMakeFileDir(self):
977 if self._MakeFileDir is None:
978 self._MakeFileDir = self.BuildDir
979 return self._MakeFileDir
980
981 ## Return build command string
982 #
983 # @retval string Build command string
984 #
985 def _GetBuildCommand(self):
986 if self._BuildCommand is None:
987 # BuildCommand should be all the same. So just get one from platform AutoGen
988 self._BuildCommand = self.AutoGenObjectList[0].BuildCommand
989 return self._BuildCommand
990
991 ## Check the PCDs token value conflict in each DEC file.
992 #
993 # Will cause build break and raise error message while two PCDs conflict.
994 #
995 # @return None
996 #
997 def _CheckAllPcdsTokenValueConflict(self):
998 for Pa in self.AutoGenObjectList:
999 for Package in Pa.PackageList:
1000 PcdList = Package.Pcds.values()
1001 PcdList.sort(lambda x, y: cmp(int(x.TokenValue, 0), int(y.TokenValue, 0)))
1002 Count = 0
1003 while (Count < len(PcdList) - 1) :
1004 Item = PcdList[Count]
1005 ItemNext = PcdList[Count + 1]
1006 #
1007 # Make sure in the same token space the TokenValue should be unique
1008 #
1009 if (int(Item.TokenValue, 0) == int(ItemNext.TokenValue, 0)):
1010 SameTokenValuePcdList = []
1011 SameTokenValuePcdList.append(Item)
1012 SameTokenValuePcdList.append(ItemNext)
1013 RemainPcdListLength = len(PcdList) - Count - 2
1014 for ValueSameCount in range(RemainPcdListLength):
1015 if int(PcdList[len(PcdList) - RemainPcdListLength + ValueSameCount].TokenValue, 0) == int(Item.TokenValue, 0):
1016 SameTokenValuePcdList.append(PcdList[len(PcdList) - RemainPcdListLength + ValueSameCount])
1017 else:
1018 break;
1019 #
1020 # Sort same token value PCD list with TokenGuid and TokenCName
1021 #
1022 SameTokenValuePcdList.sort(lambda x, y: cmp("%s.%s" % (x.TokenSpaceGuidCName, x.TokenCName), "%s.%s" % (y.TokenSpaceGuidCName, y.TokenCName)))
1023 SameTokenValuePcdListCount = 0
1024 while (SameTokenValuePcdListCount < len(SameTokenValuePcdList) - 1):
1025 Flag = False
1026 TemListItem = SameTokenValuePcdList[SameTokenValuePcdListCount]
1027 TemListItemNext = SameTokenValuePcdList[SameTokenValuePcdListCount + 1]
1028
1029 if (TemListItem.TokenSpaceGuidCName == TemListItemNext.TokenSpaceGuidCName) and (TemListItem.TokenCName != TemListItemNext.TokenCName):
1030 for PcdItem in GlobalData.MixedPcd:
1031 if (TemListItem.TokenCName, TemListItem.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem] or \
1032 (TemListItemNext.TokenCName, TemListItemNext.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:
1033 Flag = True
1034 if not Flag:
1035 EdkLogger.error(
1036 'build',
1037 FORMAT_INVALID,
1038 "The TokenValue [%s] of PCD [%s.%s] is conflict with: [%s.%s] in %s"\
1039 % (TemListItem.TokenValue, TemListItem.TokenSpaceGuidCName, TemListItem.TokenCName, TemListItemNext.TokenSpaceGuidCName, TemListItemNext.TokenCName, Package),
1040 ExtraData=None
1041 )
1042 SameTokenValuePcdListCount += 1
1043 Count += SameTokenValuePcdListCount
1044 Count += 1
1045
1046 PcdList = Package.Pcds.values()
1047 PcdList.sort(lambda x, y: cmp("%s.%s" % (x.TokenSpaceGuidCName, x.TokenCName), "%s.%s" % (y.TokenSpaceGuidCName, y.TokenCName)))
1048 Count = 0
1049 while (Count < len(PcdList) - 1) :
1050 Item = PcdList[Count]
1051 ItemNext = PcdList[Count + 1]
1052 #
1053 # Check PCDs with same TokenSpaceGuidCName.TokenCName have same token value as well.
1054 #
1055 if (Item.TokenSpaceGuidCName == ItemNext.TokenSpaceGuidCName) and (Item.TokenCName == ItemNext.TokenCName) and (int(Item.TokenValue, 0) != int(ItemNext.TokenValue, 0)):
1056 EdkLogger.error(
1057 'build',
1058 FORMAT_INVALID,
1059 "The TokenValue [%s] of PCD [%s.%s] in %s defined in two places should be same as well."\
1060 % (Item.TokenValue, Item.TokenSpaceGuidCName, Item.TokenCName, Package),
1061 ExtraData=None
1062 )
1063 Count += 1
1064 ## Generate fds command
1065 def _GenFdsCommand(self):
1066 return (GenMake.TopLevelMakefile(self)._TEMPLATE_.Replace(GenMake.TopLevelMakefile(self)._TemplateDict)).strip()
1067
1068 ## Create makefile for the platform and modules in it
1069 #
1070 # @param CreateDepsMakeFile Flag indicating if the makefile for
1071 # modules will be created as well
1072 #
1073 def CreateMakeFile(self, CreateDepsMakeFile=False):
1074 if not CreateDepsMakeFile:
1075 return
1076 for Pa in self.AutoGenObjectList:
1077 Pa.CreateMakeFile(True)
1078
1079 ## Create autogen code for platform and modules
1080 #
1081 # Since there's no autogen code for platform, this method will do nothing
1082 # if CreateModuleCodeFile is set to False.
1083 #
1084 # @param CreateDepsCodeFile Flag indicating if creating module's
1085 # autogen code file or not
1086 #
1087 def CreateCodeFile(self, CreateDepsCodeFile=False):
1088 if not CreateDepsCodeFile:
1089 return
1090 for Pa in self.AutoGenObjectList:
1091 Pa.CreateCodeFile(True)
1092
1093 ## Create AsBuilt INF file the platform
1094 #
1095 def CreateAsBuiltInf(self):
1096 return
1097
1098 Name = property(_GetName)
1099 Guid = property(_GetGuid)
1100 Version = property(_GetVersion)
1101 OutputDir = property(_GetOutputDir)
1102
1103 ToolDefinition = property(_GetToolDefinition) # toolcode : tool path
1104
1105 BuildDir = property(_GetBuildDir)
1106 FvDir = property(_GetFvDir)
1107 MakeFileDir = property(_GetMakeFileDir)
1108 BuildCommand = property(_GetBuildCommand)
1109 GenFdsCommand = property(_GenFdsCommand)
1110
1111 ## AutoGen class for platform
1112 #
1113 # PlatformAutoGen class will process the original information in platform
1114 # file in order to generate makefile for platform.
1115 #
1116 class PlatformAutoGen(AutoGen):
1117 # call super().__init__ then call the worker function with different parameter count
1118 def __init__(self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):
1119 try:
1120 self._Init
1121 except:
1122 super(PlatformAutoGen, self).__init__(self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)
1123 self._InitWorker(Workspace, MetaFile, Target, Toolchain, Arch)
1124 self._Init = True
1125 #
1126 # Used to store all PCDs for both PEI and DXE phase, in order to generate
1127 # correct PCD database
1128 #
1129 _DynaPcdList_ = []
1130 _NonDynaPcdList_ = []
1131 _PlatformPcds = {}
1132
1133 #
1134 # The priority list while override build option
1135 #
1136 PrioList = {"0x11111" : 16, # TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE (Highest)
1137 "0x01111" : 15, # ******_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
1138 "0x10111" : 14, # TARGET_*********_ARCH_COMMANDTYPE_ATTRIBUTE
1139 "0x00111" : 13, # ******_*********_ARCH_COMMANDTYPE_ATTRIBUTE
1140 "0x11011" : 12, # TARGET_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE
1141 "0x01011" : 11, # ******_TOOLCHAIN_****_COMMANDTYPE_ATTRIBUTE
1142 "0x10011" : 10, # TARGET_*********_****_COMMANDTYPE_ATTRIBUTE
1143 "0x00011" : 9, # ******_*********_****_COMMANDTYPE_ATTRIBUTE
1144 "0x11101" : 8, # TARGET_TOOLCHAIN_ARCH_***********_ATTRIBUTE
1145 "0x01101" : 7, # ******_TOOLCHAIN_ARCH_***********_ATTRIBUTE
1146 "0x10101" : 6, # TARGET_*********_ARCH_***********_ATTRIBUTE
1147 "0x00101" : 5, # ******_*********_ARCH_***********_ATTRIBUTE
1148 "0x11001" : 4, # TARGET_TOOLCHAIN_****_***********_ATTRIBUTE
1149 "0x01001" : 3, # ******_TOOLCHAIN_****_***********_ATTRIBUTE
1150 "0x10001" : 2, # TARGET_*********_****_***********_ATTRIBUTE
1151 "0x00001" : 1} # ******_*********_****_***********_ATTRIBUTE (Lowest)
1152
1153 ## Initialize PlatformAutoGen
1154 #
1155 #
1156 # @param Workspace WorkspaceAutoGen object
1157 # @param PlatformFile Platform file (DSC file)
1158 # @param Target Build target (DEBUG, RELEASE)
1159 # @param Toolchain Name of tool chain
1160 # @param Arch arch of the platform supports
1161 #
1162 def _InitWorker(self, Workspace, PlatformFile, Target, Toolchain, Arch):
1163 EdkLogger.debug(EdkLogger.DEBUG_9, "AutoGen platform [%s] [%s]" % (PlatformFile, Arch))
1164 GlobalData.gProcessingFile = "%s [%s, %s, %s]" % (PlatformFile, Arch, Toolchain, Target)
1165
1166 self.MetaFile = PlatformFile
1167 self.Workspace = Workspace
1168 self.WorkspaceDir = Workspace.WorkspaceDir
1169 self.ToolChain = Toolchain
1170 self.BuildTarget = Target
1171 self.Arch = Arch
1172 self.SourceDir = PlatformFile.SubDir
1173 self.SourceOverrideDir = None
1174 self.FdTargetList = self.Workspace.FdTargetList
1175 self.FvTargetList = self.Workspace.FvTargetList
1176 self.AllPcdList = []
1177 # get the original module/package/platform objects
1178 self.BuildDatabase = Workspace.BuildDatabase
1179 self.DscBuildDataObj = Workspace.Platform
1180 self._GuidDict = Workspace._GuidDict
1181
1182 # flag indicating if the makefile/C-code file has been created or not
1183 self.IsMakeFileCreated = False
1184 self.IsCodeFileCreated = False
1185
1186 self._Platform = None
1187 self._Name = None
1188 self._Guid = None
1189 self._Version = None
1190
1191 self._BuildRule = None
1192 self._SourceDir = None
1193 self._BuildDir = None
1194 self._OutputDir = None
1195 self._FvDir = None
1196 self._MakeFileDir = None
1197 self._FdfFile = None
1198
1199 self._PcdTokenNumber = None # (TokenCName, TokenSpaceGuidCName) : GeneratedTokenNumber
1200 self._DynamicPcdList = None # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
1201 self._NonDynamicPcdList = None # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
1202 self._NonDynamicPcdDict = {}
1203
1204 self._ToolDefinitions = None
1205 self._ToolDefFile = None # toolcode : tool path
1206 self._ToolChainFamily = None
1207 self._BuildRuleFamily = None
1208 self._BuildOption = None # toolcode : option
1209 self._EdkBuildOption = None # edktoolcode : option
1210 self._EdkIIBuildOption = None # edkiitoolcode : option
1211 self._PackageList = None
1212 self._ModuleAutoGenList = None
1213 self._LibraryAutoGenList = None
1214 self._BuildCommand = None
1215 self._AsBuildInfList = []
1216 self._AsBuildModuleList = []
1217
1218 self.VariableInfo = None
1219
1220 if GlobalData.gFdfParser is not None:
1221 self._AsBuildInfList = GlobalData.gFdfParser.Profile.InfList
1222 for Inf in self._AsBuildInfList:
1223 InfClass = PathClass(NormPath(Inf), GlobalData.gWorkspace, self.Arch)
1224 M = self.BuildDatabase[InfClass, self.Arch, self.BuildTarget, self.ToolChain]
1225 if not M.IsSupportedArch:
1226 continue
1227 self._AsBuildModuleList.append(InfClass)
1228 # get library/modules for build
1229 self.LibraryBuildDirectoryList = []
1230 self.ModuleBuildDirectoryList = []
1231
1232 return True
1233
1234 def __repr__(self):
1235 return "%s [%s]" % (self.MetaFile, self.Arch)
1236
1237 ## Create autogen code for platform and modules
1238 #
1239 # Since there's no autogen code for platform, this method will do nothing
1240 # if CreateModuleCodeFile is set to False.
1241 #
1242 # @param CreateModuleCodeFile Flag indicating if creating module's
1243 # autogen code file or not
1244 #
1245 def CreateCodeFile(self, CreateModuleCodeFile=False):
1246 # only module has code to be greated, so do nothing if CreateModuleCodeFile is False
1247 if self.IsCodeFileCreated or not CreateModuleCodeFile:
1248 return
1249
1250 for Ma in self.ModuleAutoGenList:
1251 Ma.CreateCodeFile(True)
1252
1253 # don't do this twice
1254 self.IsCodeFileCreated = True
1255
1256 ## Generate Fds Command
1257 def _GenFdsCommand(self):
1258 return self.Workspace.GenFdsCommand
1259
1260 ## Create makefile for the platform and mdoules in it
1261 #
1262 # @param CreateModuleMakeFile Flag indicating if the makefile for
1263 # modules will be created as well
1264 #
1265 def CreateMakeFile(self, CreateModuleMakeFile=False, FfsCommand = {}):
1266 if CreateModuleMakeFile:
1267 for ModuleFile in self.Platform.Modules:
1268 Ma = ModuleAutoGen(self.Workspace, ModuleFile, self.BuildTarget,
1269 self.ToolChain, self.Arch, self.MetaFile)
1270 if (ModuleFile.File, self.Arch) in FfsCommand:
1271 Ma.CreateMakeFile(True, FfsCommand[ModuleFile.File, self.Arch])
1272 else:
1273 Ma.CreateMakeFile(True)
1274 #Ma.CreateAsBuiltInf()
1275
1276 # no need to create makefile for the platform more than once
1277 if self.IsMakeFileCreated:
1278 return
1279
1280 # create library/module build dirs for platform
1281 Makefile = GenMake.PlatformMakefile(self)
1282 self.LibraryBuildDirectoryList = Makefile.GetLibraryBuildDirectoryList()
1283 self.ModuleBuildDirectoryList = Makefile.GetModuleBuildDirectoryList()
1284
1285 self.IsMakeFileCreated = True
1286
1287 ## Deal with Shared FixedAtBuild Pcds
1288 #
1289 def CollectFixedAtBuildPcds(self):
1290 for LibAuto in self.LibraryAutoGenList:
1291 FixedAtBuildPcds = {}
1292 ShareFixedAtBuildPcdsSameValue = {}
1293 for Module in LibAuto._ReferenceModules:
1294 for Pcd in Module.FixedAtBuildPcds + LibAuto.FixedAtBuildPcds:
1295 DefaultValue = Pcd.DefaultValue
1296 # Cover the case: DSC component override the Pcd value and the Pcd only used in one Lib
1297 if Pcd in Module.LibraryPcdList:
1298 Index = Module.LibraryPcdList.index(Pcd)
1299 DefaultValue = Module.LibraryPcdList[Index].DefaultValue
1300 key = ".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName))
1301 if key not in FixedAtBuildPcds:
1302 ShareFixedAtBuildPcdsSameValue[key] = True
1303 FixedAtBuildPcds[key] = DefaultValue
1304 else:
1305 if FixedAtBuildPcds[key] != DefaultValue:
1306 ShareFixedAtBuildPcdsSameValue[key] = False
1307 for Pcd in LibAuto.FixedAtBuildPcds:
1308 key = ".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName))
1309 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) not in self.NonDynamicPcdDict:
1310 continue
1311 else:
1312 DscPcd = self.NonDynamicPcdDict[(Pcd.TokenCName, Pcd.TokenSpaceGuidCName)]
1313 if DscPcd.Type != TAB_PCDS_FIXED_AT_BUILD:
1314 continue
1315 if key in ShareFixedAtBuildPcdsSameValue and ShareFixedAtBuildPcdsSameValue[key]:
1316 LibAuto.ConstPcd[key] = FixedAtBuildPcds[key]
1317
1318 def CollectVariables(self, DynamicPcdSet):
1319
1320 VpdRegionSize = 0
1321 VpdRegionBase = 0
1322 if self.Workspace.FdfFile:
1323 FdDict = self.Workspace.FdfProfile.FdDict[GlobalData.gFdfParser.CurrentFdName]
1324 for FdRegion in FdDict.RegionList:
1325 for item in FdRegion.RegionDataList:
1326 if self.Platform.VpdToolGuid.strip() and self.Platform.VpdToolGuid in item:
1327 VpdRegionSize = FdRegion.Size
1328 VpdRegionBase = FdRegion.Offset
1329 break
1330
1331
1332 VariableInfo = VariableMgr(self.DscBuildDataObj._GetDefaultStores(), self.DscBuildDataObj._GetSkuIds())
1333 VariableInfo.SetVpdRegionMaxSize(VpdRegionSize)
1334 VariableInfo.SetVpdRegionOffset(VpdRegionBase)
1335 Index = 0
1336 for Pcd in DynamicPcdSet:
1337 pcdname = ".".join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName))
1338 for SkuName in Pcd.SkuInfoList:
1339 Sku = Pcd.SkuInfoList[SkuName]
1340 SkuId = Sku.SkuId
1341 if SkuId is None or SkuId == '':
1342 continue
1343 if len(Sku.VariableName) > 0:
1344 VariableGuidStructure = Sku.VariableGuidValue
1345 VariableGuid = GuidStructureStringToGuidString(VariableGuidStructure)
1346 for StorageName in Sku.DefaultStoreDict:
1347 VariableInfo.append_variable(var_info(Index, pcdname, StorageName, SkuName, StringToArray(Sku.VariableName), VariableGuid, Sku.VariableOffset, Sku.VariableAttribute, Sku.HiiDefaultValue, Sku.DefaultStoreDict[StorageName], Pcd.DatumType))
1348 Index += 1
1349 return VariableInfo
1350
1351 def UpdateNVStoreMaxSize(self, OrgVpdFile):
1352 if self.VariableInfo:
1353 VpdMapFilePath = os.path.join(self.BuildDir, TAB_FV_DIRECTORY, "%s.map" % self.Platform.VpdToolGuid)
1354 PcdNvStoreDfBuffer = [item for item in self._DynamicPcdList if item.TokenCName == "PcdNvStoreDefaultValueBuffer" and item.TokenSpaceGuidCName == "gEfiMdeModulePkgTokenSpaceGuid"]
1355
1356 if PcdNvStoreDfBuffer:
1357 if os.path.exists(VpdMapFilePath):
1358 OrgVpdFile.Read(VpdMapFilePath)
1359 PcdItems = OrgVpdFile.GetOffset(PcdNvStoreDfBuffer[0])
1360 NvStoreOffset = PcdItems.values()[0].strip() if PcdItems else '0'
1361 else:
1362 EdkLogger.error("build", FILE_READ_FAILURE, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath)
1363
1364 NvStoreOffset = int(NvStoreOffset, 16) if NvStoreOffset.upper().startswith("0X") else int(NvStoreOffset)
1365 default_skuobj = PcdNvStoreDfBuffer[0].SkuInfoList.get(TAB_DEFAULT)
1366 maxsize = self.VariableInfo.VpdRegionSize - NvStoreOffset if self.VariableInfo.VpdRegionSize else len(default_skuobj.DefaultValue.split(","))
1367 var_data = self.VariableInfo.PatchNVStoreDefaultMaxSize(maxsize)
1368
1369 if var_data and default_skuobj:
1370 default_skuobj.DefaultValue = var_data
1371 PcdNvStoreDfBuffer[0].DefaultValue = var_data
1372 PcdNvStoreDfBuffer[0].SkuInfoList.clear()
1373 PcdNvStoreDfBuffer[0].SkuInfoList[TAB_DEFAULT] = default_skuobj
1374 PcdNvStoreDfBuffer[0].MaxDatumSize = str(len(default_skuobj.DefaultValue.split(",")))
1375
1376 return OrgVpdFile
1377
1378 ## Collect dynamic PCDs
1379 #
1380 # Gather dynamic PCDs list from each module and their settings from platform
1381 # This interface should be invoked explicitly when platform action is created.
1382 #
1383 def CollectPlatformDynamicPcds(self):
1384
1385 for key in self.Platform.Pcds:
1386 for SinglePcd in GlobalData.MixedPcd:
1387 if (self.Platform.Pcds[key].TokenCName, self.Platform.Pcds[key].TokenSpaceGuidCName) == SinglePcd:
1388 for item in GlobalData.MixedPcd[SinglePcd]:
1389 Pcd_Type = item[0].split('_')[-1]
1390 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 \
1391 (Pcd_Type == TAB_PCDS_DYNAMIC and self.Platform.Pcds[key].Type in PCD_DYNAMIC_TYPE_SET):
1392 Value = self.Platform.Pcds[key]
1393 Value.TokenCName = self.Platform.Pcds[key].TokenCName + '_' + Pcd_Type
1394 if len(key) == 2:
1395 newkey = (Value.TokenCName, key[1])
1396 elif len(key) == 3:
1397 newkey = (Value.TokenCName, key[1], key[2])
1398 del self.Platform.Pcds[key]
1399 self.Platform.Pcds[newkey] = Value
1400 break
1401 break
1402
1403 # for gathering error information
1404 NoDatumTypePcdList = set()
1405 FdfModuleList = []
1406 for InfName in self._AsBuildInfList:
1407 InfName = mws.join(self.WorkspaceDir, InfName)
1408 FdfModuleList.append(os.path.normpath(InfName))
1409 for F in self.Platform.Modules.keys():
1410 M = ModuleAutoGen(self.Workspace, F, self.BuildTarget, self.ToolChain, self.Arch, self.MetaFile)
1411 #GuidValue.update(M.Guids)
1412
1413 self.Platform.Modules[F].M = M
1414
1415 for PcdFromModule in M.ModulePcdList + M.LibraryPcdList:
1416 # make sure that the "VOID*" kind of datum has MaxDatumSize set
1417 if PcdFromModule.DatumType == TAB_VOID and not PcdFromModule.MaxDatumSize:
1418 NoDatumTypePcdList.add("%s.%s [%s]" % (PcdFromModule.TokenSpaceGuidCName, PcdFromModule.TokenCName, F))
1419
1420 # Check the PCD from Binary INF or Source INF
1421 if M.IsBinaryModule == True:
1422 PcdFromModule.IsFromBinaryInf = True
1423
1424 # Check the PCD from DSC or not
1425 PcdFromModule.IsFromDsc = (PcdFromModule.TokenCName, PcdFromModule.TokenSpaceGuidCName) in self.Platform.Pcds
1426
1427 if PcdFromModule.Type in PCD_DYNAMIC_TYPE_SET or PcdFromModule.Type in PCD_DYNAMIC_EX_TYPE_SET:
1428 if F.Path not in FdfModuleList:
1429 # If one of the Source built modules listed in the DSC is not listed
1430 # in FDF modules, and the INF lists a PCD can only use the PcdsDynamic
1431 # access method (it is only listed in the DEC file that declares the
1432 # PCD as PcdsDynamic), then build tool will report warning message
1433 # notify the PI that they are attempting to build a module that must
1434 # be included in a flash image in order to be functional. These Dynamic
1435 # PCD will not be added into the Database unless it is used by other
1436 # modules that are included in the FDF file.
1437 if PcdFromModule.Type in PCD_DYNAMIC_TYPE_SET and \
1438 PcdFromModule.IsFromBinaryInf == False:
1439 # Print warning message to let the developer make a determine.
1440 continue
1441 # If one of the Source built modules listed in the DSC is not listed in
1442 # FDF modules, and the INF lists a PCD can only use the PcdsDynamicEx
1443 # access method (it is only listed in the DEC file that declares the
1444 # PCD as PcdsDynamicEx), then DO NOT break the build; DO NOT add the
1445 # PCD to the Platform's PCD Database.
1446 if PcdFromModule.Type in PCD_DYNAMIC_EX_TYPE_SET:
1447 continue
1448 #
1449 # If a dynamic PCD used by a PEM module/PEI module & DXE module,
1450 # it should be stored in Pcd PEI database, If a dynamic only
1451 # used by DXE module, it should be stored in DXE PCD database.
1452 # The default Phase is DXE
1453 #
1454 if M.ModuleType in SUP_MODULE_SET_PEI:
1455 PcdFromModule.Phase = "PEI"
1456 if PcdFromModule not in self._DynaPcdList_:
1457 self._DynaPcdList_.append(PcdFromModule)
1458 elif PcdFromModule.Phase == 'PEI':
1459 # overwrite any the same PCD existing, if Phase is PEI
1460 Index = self._DynaPcdList_.index(PcdFromModule)
1461 self._DynaPcdList_[Index] = PcdFromModule
1462 elif PcdFromModule not in self._NonDynaPcdList_:
1463 self._NonDynaPcdList_.append(PcdFromModule)
1464 elif PcdFromModule in self._NonDynaPcdList_ and PcdFromModule.IsFromBinaryInf == True:
1465 Index = self._NonDynaPcdList_.index(PcdFromModule)
1466 if self._NonDynaPcdList_[Index].IsFromBinaryInf == False:
1467 #The PCD from Binary INF will override the same one from source INF
1468 self._NonDynaPcdList_.remove (self._NonDynaPcdList_[Index])
1469 PcdFromModule.Pending = False
1470 self._NonDynaPcdList_.append (PcdFromModule)
1471 DscModuleSet = {os.path.normpath(ModuleInf.Path) for ModuleInf in self.Platform.Modules}
1472 # add the PCD from modules that listed in FDF but not in DSC to Database
1473 for InfName in FdfModuleList:
1474 if InfName not in DscModuleSet:
1475 InfClass = PathClass(InfName)
1476 M = self.BuildDatabase[InfClass, self.Arch, self.BuildTarget, self.ToolChain]
1477 # If a module INF in FDF but not in current arch's DSC module list, it must be module (either binary or source)
1478 # for different Arch. PCDs in source module for different Arch is already added before, so skip the source module here.
1479 # For binary module, if in current arch, we need to list the PCDs into database.
1480 if not M.IsSupportedArch:
1481 continue
1482 # Override the module PCD setting by platform setting
1483 ModulePcdList = self.ApplyPcdSetting(M, M.Pcds)
1484 for PcdFromModule in ModulePcdList:
1485 PcdFromModule.IsFromBinaryInf = True
1486 PcdFromModule.IsFromDsc = False
1487 # Only allow the DynamicEx and Patchable PCD in AsBuild INF
1488 if PcdFromModule.Type not in PCD_DYNAMIC_EX_TYPE_SET and PcdFromModule.Type not in TAB_PCDS_PATCHABLE_IN_MODULE:
1489 EdkLogger.error("build", AUTOGEN_ERROR, "PCD setting error",
1490 File=self.MetaFile,
1491 ExtraData="\n\tExisted %s PCD %s in:\n\t\t%s\n"
1492 % (PcdFromModule.Type, PcdFromModule.TokenCName, InfName))
1493 # make sure that the "VOID*" kind of datum has MaxDatumSize set
1494 if PcdFromModule.DatumType == TAB_VOID and not PcdFromModule.MaxDatumSize:
1495 NoDatumTypePcdList.add("%s.%s [%s]" % (PcdFromModule.TokenSpaceGuidCName, PcdFromModule.TokenCName, InfName))
1496 if M.ModuleType in SUP_MODULE_SET_PEI:
1497 PcdFromModule.Phase = "PEI"
1498 if PcdFromModule not in self._DynaPcdList_ and PcdFromModule.Type in PCD_DYNAMIC_EX_TYPE_SET:
1499 self._DynaPcdList_.append(PcdFromModule)
1500 elif PcdFromModule not in self._NonDynaPcdList_ and PcdFromModule.Type in TAB_PCDS_PATCHABLE_IN_MODULE:
1501 self._NonDynaPcdList_.append(PcdFromModule)
1502 if PcdFromModule in self._DynaPcdList_ and PcdFromModule.Phase == 'PEI' and PcdFromModule.Type in PCD_DYNAMIC_EX_TYPE_SET:
1503 # Overwrite the phase of any the same PCD existing, if Phase is PEI.
1504 # It is to solve the case that a dynamic PCD used by a PEM module/PEI
1505 # module & DXE module at a same time.
1506 # Overwrite the type of the PCDs in source INF by the type of AsBuild
1507 # INF file as DynamicEx.
1508 Index = self._DynaPcdList_.index(PcdFromModule)
1509 self._DynaPcdList_[Index].Phase = PcdFromModule.Phase
1510 self._DynaPcdList_[Index].Type = PcdFromModule.Type
1511 for PcdFromModule in self._NonDynaPcdList_:
1512 # If a PCD is not listed in the DSC file, but binary INF files used by
1513 # this platform all (that use this PCD) list the PCD in a [PatchPcds]
1514 # section, AND all source INF files used by this platform the build
1515 # that use the PCD list the PCD in either a [Pcds] or [PatchPcds]
1516 # section, then the tools must NOT add the PCD to the Platform's PCD
1517 # Database; the build must assign the access method for this PCD as
1518 # PcdsPatchableInModule.
1519 if PcdFromModule not in self._DynaPcdList_:
1520 continue
1521 Index = self._DynaPcdList_.index(PcdFromModule)
1522 if PcdFromModule.IsFromDsc == False and \
1523 PcdFromModule.Type in TAB_PCDS_PATCHABLE_IN_MODULE and \
1524 PcdFromModule.IsFromBinaryInf == True and \
1525 self._DynaPcdList_[Index].IsFromBinaryInf == False:
1526 Index = self._DynaPcdList_.index(PcdFromModule)
1527 self._DynaPcdList_.remove (self._DynaPcdList_[Index])
1528
1529 # print out error information and break the build, if error found
1530 if len(NoDatumTypePcdList) > 0:
1531 NoDatumTypePcdListString = "\n\t\t".join(NoDatumTypePcdList)
1532 EdkLogger.error("build", AUTOGEN_ERROR, "PCD setting error",
1533 File=self.MetaFile,
1534 ExtraData="\n\tPCD(s) without MaxDatumSize:\n\t\t%s\n"
1535 % NoDatumTypePcdListString)
1536 self._NonDynamicPcdList = self._NonDynaPcdList_
1537 self._DynamicPcdList = self._DynaPcdList_
1538 #
1539 # Sort dynamic PCD list to:
1540 # 1) If PCD's datum type is VOID* and value is unicode string which starts with L, the PCD item should
1541 # try to be put header of dynamicd List
1542 # 2) If PCD is HII type, the PCD item should be put after unicode type PCD
1543 #
1544 # The reason of sorting is make sure the unicode string is in double-byte alignment in string table.
1545 #
1546 UnicodePcdArray = set()
1547 HiiPcdArray = set()
1548 OtherPcdArray = set()
1549 VpdPcdDict = {}
1550 VpdFile = VpdInfoFile.VpdInfoFile()
1551 NeedProcessVpdMapFile = False
1552
1553 for pcd in self.Platform.Pcds:
1554 if pcd not in self._PlatformPcds:
1555 self._PlatformPcds[pcd] = self.Platform.Pcds[pcd]
1556
1557 for item in self._PlatformPcds:
1558 if self._PlatformPcds[item].DatumType and self._PlatformPcds[item].DatumType not in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64, TAB_VOID, "BOOLEAN"]:
1559 self._PlatformPcds[item].DatumType = TAB_VOID
1560
1561 if (self.Workspace.ArchList[-1] == self.Arch):
1562 for Pcd in self._DynamicPcdList:
1563 # just pick the a value to determine whether is unicode string type
1564 Sku = Pcd.SkuInfoList.values()[0]
1565 Sku.VpdOffset = Sku.VpdOffset.strip()
1566
1567 if Pcd.DatumType not in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64, TAB_VOID, "BOOLEAN"]:
1568 Pcd.DatumType = TAB_VOID
1569
1570 # if found PCD which datum value is unicode string the insert to left size of UnicodeIndex
1571 # if found HII type PCD then insert to right of UnicodeIndex
1572 if Pcd.Type in [TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_VPD]:
1573 VpdPcdDict[(Pcd.TokenCName, Pcd.TokenSpaceGuidCName)] = Pcd
1574
1575 #Collect DynamicHii PCD values and assign it to DynamicExVpd PCD gEfiMdeModulePkgTokenSpaceGuid.PcdNvStoreDefaultValueBuffer
1576 PcdNvStoreDfBuffer = VpdPcdDict.get(("PcdNvStoreDefaultValueBuffer", "gEfiMdeModulePkgTokenSpaceGuid"))
1577 if PcdNvStoreDfBuffer:
1578 self.VariableInfo = self.CollectVariables(self._DynamicPcdList)
1579 vardump = self.VariableInfo.dump()
1580 if vardump:
1581 PcdNvStoreDfBuffer.DefaultValue = vardump
1582 for skuname in PcdNvStoreDfBuffer.SkuInfoList:
1583 PcdNvStoreDfBuffer.SkuInfoList[skuname].DefaultValue = vardump
1584 PcdNvStoreDfBuffer.MaxDatumSize = str(len(vardump.split(",")))
1585
1586 PlatformPcds = sorted(self._PlatformPcds.keys())
1587 #
1588 # Add VPD type PCD into VpdFile and determine whether the VPD PCD need to be fixed up.
1589 #
1590 VpdSkuMap = {}
1591 for PcdKey in PlatformPcds:
1592 Pcd = self._PlatformPcds[PcdKey]
1593 if Pcd.Type in [TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_VPD] and \
1594 PcdKey in VpdPcdDict:
1595 Pcd = VpdPcdDict[PcdKey]
1596 SkuValueMap = {}
1597 DefaultSku = Pcd.SkuInfoList.get(TAB_DEFAULT)
1598 if DefaultSku:
1599 PcdValue = DefaultSku.DefaultValue
1600 if PcdValue not in SkuValueMap:
1601 SkuValueMap[PcdValue] = []
1602 VpdFile.Add(Pcd, TAB_DEFAULT, DefaultSku.VpdOffset)
1603 SkuValueMap[PcdValue].append(DefaultSku)
1604
1605 for (SkuName, Sku) in Pcd.SkuInfoList.items():
1606 Sku.VpdOffset = Sku.VpdOffset.strip()
1607 PcdValue = Sku.DefaultValue
1608 if PcdValue == "":
1609 PcdValue = Pcd.DefaultValue
1610 if Sku.VpdOffset != '*':
1611 if PcdValue.startswith("{"):
1612 Alignment = 8
1613 elif PcdValue.startswith("L"):
1614 Alignment = 2
1615 else:
1616 Alignment = 1
1617 try:
1618 VpdOffset = int(Sku.VpdOffset)
1619 except:
1620 try:
1621 VpdOffset = int(Sku.VpdOffset, 16)
1622 except:
1623 EdkLogger.error("build", FORMAT_INVALID, "Invalid offset value %s for PCD %s.%s." % (Sku.VpdOffset, Pcd.TokenSpaceGuidCName, Pcd.TokenCName))
1624 if VpdOffset % Alignment != 0:
1625 if PcdValue.startswith("{"):
1626 EdkLogger.warn("build", "The offset value of PCD %s.%s is not 8-byte aligned!" %(Pcd.TokenSpaceGuidCName, Pcd.TokenCName), File=self.MetaFile)
1627 else:
1628 EdkLogger.error("build", FORMAT_INVALID, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName, Alignment))
1629 if PcdValue not in SkuValueMap:
1630 SkuValueMap[PcdValue] = []
1631 VpdFile.Add(Pcd, SkuName, Sku.VpdOffset)
1632 SkuValueMap[PcdValue].append(Sku)
1633 # if the offset of a VPD is *, then it need to be fixed up by third party tool.
1634 if not NeedProcessVpdMapFile and Sku.VpdOffset == "*":
1635 NeedProcessVpdMapFile = True
1636 if self.Platform.VpdToolGuid is None or self.Platform.VpdToolGuid == '':
1637 EdkLogger.error("Build", FILE_NOT_FOUND, \
1638 "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.")
1639
1640 VpdSkuMap[PcdKey] = SkuValueMap
1641 #
1642 # Fix the PCDs define in VPD PCD section that never referenced by module.
1643 # An example is PCD for signature usage.
1644 #
1645 for DscPcd in PlatformPcds:
1646 DscPcdEntry = self._PlatformPcds[DscPcd]
1647 if DscPcdEntry.Type in [TAB_PCDS_DYNAMIC_VPD, TAB_PCDS_DYNAMIC_EX_VPD]:
1648 if not (self.Platform.VpdToolGuid is None or self.Platform.VpdToolGuid == ''):
1649 FoundFlag = False
1650 for VpdPcd in VpdFile._VpdArray:
1651 # This PCD has been referenced by module
1652 if (VpdPcd.TokenSpaceGuidCName == DscPcdEntry.TokenSpaceGuidCName) and \
1653 (VpdPcd.TokenCName == DscPcdEntry.TokenCName):
1654 FoundFlag = True
1655
1656 # Not found, it should be signature
1657 if not FoundFlag :
1658 # just pick the a value to determine whether is unicode string type
1659 SkuValueMap = {}
1660 SkuObjList = DscPcdEntry.SkuInfoList.items()
1661 DefaultSku = DscPcdEntry.SkuInfoList.get(TAB_DEFAULT)
1662 if DefaultSku:
1663 defaultindex = SkuObjList.index((TAB_DEFAULT, DefaultSku))
1664 SkuObjList[0], SkuObjList[defaultindex] = SkuObjList[defaultindex], SkuObjList[0]
1665 for (SkuName, Sku) in SkuObjList:
1666 Sku.VpdOffset = Sku.VpdOffset.strip()
1667
1668 # Need to iterate DEC pcd information to get the value & datumtype
1669 for eachDec in self.PackageList:
1670 for DecPcd in eachDec.Pcds:
1671 DecPcdEntry = eachDec.Pcds[DecPcd]
1672 if (DecPcdEntry.TokenSpaceGuidCName == DscPcdEntry.TokenSpaceGuidCName) and \
1673 (DecPcdEntry.TokenCName == DscPcdEntry.TokenCName):
1674 # Print warning message to let the developer make a determine.
1675 EdkLogger.warn("build", "Unreferenced vpd pcd used!",
1676 File=self.MetaFile, \
1677 ExtraData = "PCD: %s.%s used in the DSC file %s is unreferenced." \
1678 %(DscPcdEntry.TokenSpaceGuidCName, DscPcdEntry.TokenCName, self.Platform.MetaFile.Path))
1679
1680 DscPcdEntry.DatumType = DecPcdEntry.DatumType
1681 DscPcdEntry.DefaultValue = DecPcdEntry.DefaultValue
1682 DscPcdEntry.TokenValue = DecPcdEntry.TokenValue
1683 DscPcdEntry.TokenSpaceGuidValue = eachDec.Guids[DecPcdEntry.TokenSpaceGuidCName]
1684 # Only fix the value while no value provided in DSC file.
1685 if not Sku.DefaultValue:
1686 DscPcdEntry.SkuInfoList[DscPcdEntry.SkuInfoList.keys()[0]].DefaultValue = DecPcdEntry.DefaultValue
1687
1688 if DscPcdEntry not in self._DynamicPcdList:
1689 self._DynamicPcdList.append(DscPcdEntry)
1690 Sku.VpdOffset = Sku.VpdOffset.strip()
1691 PcdValue = Sku.DefaultValue
1692 if PcdValue == "":
1693 PcdValue = DscPcdEntry.DefaultValue
1694 if Sku.VpdOffset != '*':
1695 if PcdValue.startswith("{"):
1696 Alignment = 8
1697 elif PcdValue.startswith("L"):
1698 Alignment = 2
1699 else:
1700 Alignment = 1
1701 try:
1702 VpdOffset = int(Sku.VpdOffset)
1703 except:
1704 try:
1705 VpdOffset = int(Sku.VpdOffset, 16)
1706 except:
1707 EdkLogger.error("build", FORMAT_INVALID, "Invalid offset value %s for PCD %s.%s." % (Sku.VpdOffset, DscPcdEntry.TokenSpaceGuidCName, DscPcdEntry.TokenCName))
1708 if VpdOffset % Alignment != 0:
1709 if PcdValue.startswith("{"):
1710 EdkLogger.warn("build", "The offset value of PCD %s.%s is not 8-byte aligned!" %(DscPcdEntry.TokenSpaceGuidCName, DscPcdEntry.TokenCName), File=self.MetaFile)
1711 else:
1712 EdkLogger.error("build", FORMAT_INVALID, 'The offset value of PCD %s.%s should be %s-byte aligned.' % (DscPcdEntry.TokenSpaceGuidCName, DscPcdEntry.TokenCName, Alignment))
1713 if PcdValue not in SkuValueMap:
1714 SkuValueMap[PcdValue] = []
1715 VpdFile.Add(DscPcdEntry, SkuName, Sku.VpdOffset)
1716 SkuValueMap[PcdValue].append(Sku)
1717 if not NeedProcessVpdMapFile and Sku.VpdOffset == "*":
1718 NeedProcessVpdMapFile = True
1719 if DscPcdEntry.DatumType == TAB_VOID and PcdValue.startswith("L"):
1720 UnicodePcdArray.add(DscPcdEntry)
1721 elif len(Sku.VariableName) > 0:
1722 HiiPcdArray.add(DscPcdEntry)
1723 else:
1724 OtherPcdArray.add(DscPcdEntry)
1725
1726 # if the offset of a VPD is *, then it need to be fixed up by third party tool.
1727 VpdSkuMap[DscPcd] = SkuValueMap
1728 if (self.Platform.FlashDefinition is None or self.Platform.FlashDefinition == '') and \
1729 VpdFile.GetCount() != 0:
1730 EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE,
1731 "Fail to get FLASH_DEFINITION definition in DSC file %s which is required when DSC contains VPD PCD." % str(self.Platform.MetaFile))
1732
1733 if VpdFile.GetCount() != 0:
1734
1735 self.FixVpdOffset(VpdFile)
1736
1737 self.FixVpdOffset(self.UpdateNVStoreMaxSize(VpdFile))
1738
1739 # Process VPD map file generated by third party BPDG tool
1740 if NeedProcessVpdMapFile:
1741 VpdMapFilePath = os.path.join(self.BuildDir, TAB_FV_DIRECTORY, "%s.map" % self.Platform.VpdToolGuid)
1742 if os.path.exists(VpdMapFilePath):
1743 VpdFile.Read(VpdMapFilePath)
1744
1745 # Fixup "*" offset
1746 for pcd in VpdSkuMap:
1747 vpdinfo = VpdFile.GetVpdInfo(pcd)
1748 if vpdinfo is None:
1749 # just pick the a value to determine whether is unicode string type
1750 continue
1751 for pcdvalue in VpdSkuMap[pcd]:
1752 for sku in VpdSkuMap[pcd][pcdvalue]:
1753 for item in vpdinfo:
1754 if item[2] == pcdvalue:
1755 sku.VpdOffset = item[1]
1756 else:
1757 EdkLogger.error("build", FILE_READ_FAILURE, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath)
1758
1759 # Delete the DynamicPcdList At the last time enter into this function
1760 for Pcd in self._DynamicPcdList:
1761 # just pick the a value to determine whether is unicode string type
1762 Sku = Pcd.SkuInfoList.values()[0]
1763 Sku.VpdOffset = Sku.VpdOffset.strip()
1764
1765 if Pcd.DatumType not in [TAB_UINT8, TAB_UINT16, TAB_UINT32, TAB_UINT64, TAB_VOID, "BOOLEAN"]:
1766 Pcd.DatumType = TAB_VOID
1767
1768 PcdValue = Sku.DefaultValue
1769 if Pcd.DatumType == TAB_VOID and PcdValue.startswith("L"):
1770 # if found PCD which datum value is unicode string the insert to left size of UnicodeIndex
1771 UnicodePcdArray.add(Pcd)
1772 elif len(Sku.VariableName) > 0:
1773 # if found HII type PCD then insert to right of UnicodeIndex
1774 HiiPcdArray.add(Pcd)
1775 else:
1776 OtherPcdArray.add(Pcd)
1777 del self._DynamicPcdList[:]
1778 self._DynamicPcdList.extend(list(UnicodePcdArray))
1779 self._DynamicPcdList.extend(list(HiiPcdArray))
1780 self._DynamicPcdList.extend(list(OtherPcdArray))
1781 allskuset = [(SkuName, Sku.SkuId) for pcd in self._DynamicPcdList for (SkuName, Sku) in pcd.SkuInfoList.items()]
1782 for pcd in self._DynamicPcdList:
1783 if len(pcd.SkuInfoList) == 1:
1784 for (SkuName, SkuId) in allskuset:
1785 if type(SkuId) in (str, unicode) and eval(SkuId) == 0 or SkuId == 0:
1786 continue
1787 pcd.SkuInfoList[SkuName] = copy.deepcopy(pcd.SkuInfoList[TAB_DEFAULT])
1788 pcd.SkuInfoList[SkuName].SkuId = SkuId
1789 self.AllPcdList = self._NonDynamicPcdList + self._DynamicPcdList
1790
1791 def FixVpdOffset(self, VpdFile ):
1792 FvPath = os.path.join(self.BuildDir, TAB_FV_DIRECTORY)
1793 if not os.path.exists(FvPath):
1794 try:
1795 os.makedirs(FvPath)
1796 except:
1797 EdkLogger.error("build", FILE_WRITE_FAILURE, "Fail to create FV folder under %s" % self.BuildDir)
1798
1799 VpdFilePath = os.path.join(FvPath, "%s.txt" % self.Platform.VpdToolGuid)
1800
1801 if VpdFile.Write(VpdFilePath):
1802 # retrieve BPDG tool's path from tool_def.txt according to VPD_TOOL_GUID defined in DSC file.
1803 BPDGToolName = None
1804 for ToolDef in self.ToolDefinition.values():
1805 if TAB_GUID in ToolDef and ToolDef[TAB_GUID] == self.Platform.VpdToolGuid:
1806 if "PATH" not in ToolDef:
1807 EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "PATH attribute was not provided for BPDG guid tool %s in tools_def.txt" % self.Platform.VpdToolGuid)
1808 BPDGToolName = ToolDef["PATH"]
1809 break
1810 # Call third party GUID BPDG tool.
1811 if BPDGToolName is not None:
1812 VpdInfoFile.CallExtenalBPDGTool(BPDGToolName, VpdFilePath)
1813 else:
1814 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.")
1815
1816 ## Return the platform build data object
1817 def _GetPlatform(self):
1818 if self._Platform is None:
1819 self._Platform = self.BuildDatabase[self.MetaFile, self.Arch, self.BuildTarget, self.ToolChain]
1820 return self._Platform
1821
1822 ## Return platform name
1823 def _GetName(self):
1824 return self.Platform.PlatformName
1825
1826 ## Return the meta file GUID
1827 def _GetGuid(self):
1828 return self.Platform.Guid
1829
1830 ## Return the platform version
1831 def _GetVersion(self):
1832 return self.Platform.Version
1833
1834 ## Return the FDF file name
1835 def _GetFdfFile(self):
1836 if self._FdfFile is None:
1837 if self.Workspace.FdfFile != "":
1838 self._FdfFile= mws.join(self.WorkspaceDir, self.Workspace.FdfFile)
1839 else:
1840 self._FdfFile = ''
1841 return self._FdfFile
1842
1843 ## Return the build output directory platform specifies
1844 def _GetOutputDir(self):
1845 return self.Platform.OutputDirectory
1846
1847 ## Return the directory to store all intermediate and final files built
1848 def _GetBuildDir(self):
1849 if self._BuildDir is None:
1850 if os.path.isabs(self.OutputDir):
1851 self._BuildDir = path.join(
1852 path.abspath(self.OutputDir),
1853 self.BuildTarget + "_" + self.ToolChain,
1854 )
1855 else:
1856 self._BuildDir = path.join(
1857 self.WorkspaceDir,
1858 self.OutputDir,
1859 self.BuildTarget + "_" + self.ToolChain,
1860 )
1861 GlobalData.gBuildDirectory = self._BuildDir
1862 return self._BuildDir
1863
1864 ## Return directory of platform makefile
1865 #
1866 # @retval string Makefile directory
1867 #
1868 def _GetMakeFileDir(self):
1869 if self._MakeFileDir is None:
1870 self._MakeFileDir = path.join(self.BuildDir, self.Arch)
1871 return self._MakeFileDir
1872
1873 ## Return build command string
1874 #
1875 # @retval string Build command string
1876 #
1877 def _GetBuildCommand(self):
1878 if self._BuildCommand is None:
1879 self._BuildCommand = []
1880 if "MAKE" in self.ToolDefinition and "PATH" in self.ToolDefinition["MAKE"]:
1881 self._BuildCommand += SplitOption(self.ToolDefinition["MAKE"]["PATH"])
1882 if "FLAGS" in self.ToolDefinition["MAKE"]:
1883 NewOption = self.ToolDefinition["MAKE"]["FLAGS"].strip()
1884 if NewOption != '':
1885 self._BuildCommand += SplitOption(NewOption)
1886 if "MAKE" in self.EdkIIBuildOption:
1887 if "FLAGS" in self.EdkIIBuildOption["MAKE"]:
1888 Flags = self.EdkIIBuildOption["MAKE"]["FLAGS"]
1889 if Flags.startswith('='):
1890 self._BuildCommand = [self._BuildCommand[0]] + [Flags[1:]]
1891 else:
1892 self._BuildCommand.append(Flags)
1893 return self._BuildCommand
1894
1895 ## Get tool chain definition
1896 #
1897 # Get each tool defition for given tool chain from tools_def.txt and platform
1898 #
1899 def _GetToolDefinition(self):
1900 if self._ToolDefinitions is None:
1901 ToolDefinition = self.Workspace.ToolDef.ToolsDefTxtDictionary
1902 if TAB_TOD_DEFINES_COMMAND_TYPE not in self.Workspace.ToolDef.ToolsDefTxtDatabase:
1903 EdkLogger.error('build', RESOURCE_NOT_AVAILABLE, "No tools found in configuration",
1904 ExtraData="[%s]" % self.MetaFile)
1905 self._ToolDefinitions = {}
1906 DllPathList = set()
1907 for Def in ToolDefinition:
1908 Target, Tag, Arch, Tool, Attr = Def.split("_")
1909 if Target != self.BuildTarget or Tag != self.ToolChain or Arch != self.Arch:
1910 continue
1911
1912 Value = ToolDefinition[Def]
1913 # don't record the DLL
1914 if Attr == "DLL":
1915 DllPathList.add(Value)
1916 continue
1917
1918 if Tool not in self._ToolDefinitions:
1919 self._ToolDefinitions[Tool] = {}
1920 self._ToolDefinitions[Tool][Attr] = Value
1921
1922 ToolsDef = ''
1923 if GlobalData.gOptions.SilentMode and "MAKE" in self._ToolDefinitions:
1924 if "FLAGS" not in self._ToolDefinitions["MAKE"]:
1925 self._ToolDefinitions["MAKE"]["FLAGS"] = ""
1926 self._ToolDefinitions["MAKE"]["FLAGS"] += " -s"
1927 MakeFlags = ''
1928 for Tool in self._ToolDefinitions:
1929 for Attr in self._ToolDefinitions[Tool]:
1930 Value = self._ToolDefinitions[Tool][Attr]
1931 if Tool in self.BuildOption and Attr in self.BuildOption[Tool]:
1932 # check if override is indicated
1933 if self.BuildOption[Tool][Attr].startswith('='):
1934 Value = self.BuildOption[Tool][Attr][1:]
1935 else:
1936 if Attr != 'PATH':
1937 Value += " " + self.BuildOption[Tool][Attr]
1938 else:
1939 Value = self.BuildOption[Tool][Attr]
1940
1941 if Attr == "PATH":
1942 # Don't put MAKE definition in the file
1943 if Tool != "MAKE":
1944 ToolsDef += "%s = %s\n" % (Tool, Value)
1945 elif Attr != "DLL":
1946 # Don't put MAKE definition in the file
1947 if Tool == "MAKE":
1948 if Attr == "FLAGS":
1949 MakeFlags = Value
1950 else:
1951 ToolsDef += "%s_%s = %s\n" % (Tool, Attr, Value)
1952 ToolsDef += "\n"
1953
1954 SaveFileOnChange(self.ToolDefinitionFile, ToolsDef)
1955 for DllPath in DllPathList:
1956 os.environ["PATH"] = DllPath + os.pathsep + os.environ["PATH"]
1957 os.environ["MAKE_FLAGS"] = MakeFlags
1958
1959 return self._ToolDefinitions
1960
1961 ## Return the paths of tools
1962 def _GetToolDefFile(self):
1963 if self._ToolDefFile is None:
1964 self._ToolDefFile = os.path.join(self.MakeFileDir, "TOOLS_DEF." + self.Arch)
1965 return self._ToolDefFile
1966
1967 ## Retrieve the toolchain family of given toolchain tag. Default to 'MSFT'.
1968 def _GetToolChainFamily(self):
1969 if self._ToolChainFamily is None:
1970 ToolDefinition = self.Workspace.ToolDef.ToolsDefTxtDatabase
1971 if TAB_TOD_DEFINES_FAMILY not in ToolDefinition \
1972 or self.ToolChain not in ToolDefinition[TAB_TOD_DEFINES_FAMILY] \
1973 or not ToolDefinition[TAB_TOD_DEFINES_FAMILY][self.ToolChain]:
1974 EdkLogger.verbose("No tool chain family found in configuration for %s. Default to MSFT." \
1975 % self.ToolChain)
1976 self._ToolChainFamily = "MSFT"
1977 else:
1978 self._ToolChainFamily = ToolDefinition[TAB_TOD_DEFINES_FAMILY][self.ToolChain]
1979 return self._ToolChainFamily
1980
1981 def _GetBuildRuleFamily(self):
1982 if self._BuildRuleFamily is None:
1983 ToolDefinition = self.Workspace.ToolDef.ToolsDefTxtDatabase
1984 if TAB_TOD_DEFINES_BUILDRULEFAMILY not in ToolDefinition \
1985 or self.ToolChain not in ToolDefinition[TAB_TOD_DEFINES_BUILDRULEFAMILY] \
1986 or not ToolDefinition[TAB_TOD_DEFINES_BUILDRULEFAMILY][self.ToolChain]:
1987 EdkLogger.verbose("No tool chain family found in configuration for %s. Default to MSFT." \
1988 % self.ToolChain)
1989 self._BuildRuleFamily = "MSFT"
1990 else:
1991 self._BuildRuleFamily = ToolDefinition[TAB_TOD_DEFINES_BUILDRULEFAMILY][self.ToolChain]
1992 return self._BuildRuleFamily
1993
1994 ## Return the build options specific for all modules in this platform
1995 def _GetBuildOptions(self):
1996 if self._BuildOption is None:
1997 self._BuildOption = self._ExpandBuildOption(self.Platform.BuildOptions)
1998 return self._BuildOption
1999
2000 ## Return the build options specific for EDK modules in this platform
2001 def _GetEdkBuildOptions(self):
2002 if self._EdkBuildOption is None:
2003 self._EdkBuildOption = self._ExpandBuildOption(self.Platform.BuildOptions, EDK_NAME)
2004 return self._EdkBuildOption
2005
2006 ## Return the build options specific for EDKII modules in this platform
2007 def _GetEdkIIBuildOptions(self):
2008 if self._EdkIIBuildOption is None:
2009 self._EdkIIBuildOption = self._ExpandBuildOption(self.Platform.BuildOptions, EDKII_NAME)
2010 return self._EdkIIBuildOption
2011
2012 ## Parse build_rule.txt in Conf Directory.
2013 #
2014 # @retval BuildRule object
2015 #
2016 def _GetBuildRule(self):
2017 if self._BuildRule is None:
2018 BuildRuleFile = None
2019 if TAB_TAT_DEFINES_BUILD_RULE_CONF in self.Workspace.TargetTxt.TargetTxtDictionary:
2020 BuildRuleFile = self.Workspace.TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_BUILD_RULE_CONF]
2021 if not BuildRuleFile:
2022 BuildRuleFile = gDefaultBuildRuleFile
2023 self._BuildRule = BuildRule(BuildRuleFile)
2024 if self._BuildRule._FileVersion == "":
2025 self._BuildRule._FileVersion = AutoGenReqBuildRuleVerNum
2026 else:
2027 if self._BuildRule._FileVersion < AutoGenReqBuildRuleVerNum :
2028 # If Build Rule's version is less than the version number required by the tools, halting the build.
2029 EdkLogger.error("build", AUTOGEN_ERROR,
2030 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])"\
2031 % (self._BuildRule._FileVersion, AutoGenReqBuildRuleVerNum))
2032
2033 return self._BuildRule
2034
2035 ## Summarize the packages used by modules in this platform
2036 def _GetPackageList(self):
2037 if self._PackageList is None:
2038 self._PackageList = set()
2039 for La in self.LibraryAutoGenList:
2040 self._PackageList.update(La.DependentPackageList)
2041 for Ma in self.ModuleAutoGenList:
2042 self._PackageList.update(Ma.DependentPackageList)
2043 #Collect package set information from INF of FDF
2044 PkgSet = set()
2045 for ModuleFile in self._AsBuildModuleList:
2046 if ModuleFile in self.Platform.Modules:
2047 continue
2048 ModuleData = self.BuildDatabase[ModuleFile, self.Arch, self.BuildTarget, self.ToolChain]
2049 PkgSet.update(ModuleData.Packages)
2050 self._PackageList = list(self._PackageList) + list (PkgSet)
2051 return self._PackageList
2052
2053 def _GetNonDynamicPcdDict(self):
2054 if self._NonDynamicPcdDict:
2055 return self._NonDynamicPcdDict
2056 for Pcd in self.NonDynamicPcdList:
2057 self._NonDynamicPcdDict[(Pcd.TokenCName, Pcd.TokenSpaceGuidCName)] = Pcd
2058 return self._NonDynamicPcdDict
2059
2060 ## Get list of non-dynamic PCDs
2061 def _GetNonDynamicPcdList(self):
2062 if self._NonDynamicPcdList is None:
2063 self.CollectPlatformDynamicPcds()
2064 return self._NonDynamicPcdList
2065
2066 ## Get list of dynamic PCDs
2067 def _GetDynamicPcdList(self):
2068 if self._DynamicPcdList is None:
2069 self.CollectPlatformDynamicPcds()
2070 return self._DynamicPcdList
2071
2072 ## Generate Token Number for all PCD
2073 def _GetPcdTokenNumbers(self):
2074 if self._PcdTokenNumber is None:
2075 self._PcdTokenNumber = OrderedDict()
2076 TokenNumber = 1
2077 #
2078 # Make the Dynamic and DynamicEx PCD use within different TokenNumber area.
2079 # Such as:
2080 #
2081 # Dynamic PCD:
2082 # TokenNumber 0 ~ 10
2083 # DynamicEx PCD:
2084 # TokeNumber 11 ~ 20
2085 #
2086 for Pcd in self.DynamicPcdList:
2087 if Pcd.Phase == "PEI" and Pcd.Type in PCD_DYNAMIC_TYPE_SET:
2088 EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))
2089 self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber
2090 TokenNumber += 1
2091
2092 for Pcd in self.DynamicPcdList:
2093 if Pcd.Phase == "PEI" and Pcd.Type in PCD_DYNAMIC_EX_TYPE_SET:
2094 EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))
2095 self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber
2096 TokenNumber += 1
2097
2098 for Pcd in self.DynamicPcdList:
2099 if Pcd.Phase == "DXE" and Pcd.Type in PCD_DYNAMIC_TYPE_SET:
2100 EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))
2101 self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber
2102 TokenNumber += 1
2103
2104 for Pcd in self.DynamicPcdList:
2105 if Pcd.Phase == "DXE" and Pcd.Type in PCD_DYNAMIC_EX_TYPE_SET:
2106 EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))
2107 self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber
2108 TokenNumber += 1
2109
2110 for Pcd in self.NonDynamicPcdList:
2111 self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber
2112 TokenNumber += 1
2113 return self._PcdTokenNumber
2114
2115 ## Summarize ModuleAutoGen objects of all modules/libraries to be built for this platform
2116 def _GetAutoGenObjectList(self):
2117 self._ModuleAutoGenList = []
2118 self._LibraryAutoGenList = []
2119 for ModuleFile in self.Platform.Modules:
2120 Ma = ModuleAutoGen(
2121 self.Workspace,
2122 ModuleFile,
2123 self.BuildTarget,
2124 self.ToolChain,
2125 self.Arch,
2126 self.MetaFile
2127 )
2128 if Ma not in self._ModuleAutoGenList:
2129 self._ModuleAutoGenList.append(Ma)
2130 for La in Ma.LibraryAutoGenList:
2131 if La not in self._LibraryAutoGenList:
2132 self._LibraryAutoGenList.append(La)
2133 if Ma not in La._ReferenceModules:
2134 La._ReferenceModules.append(Ma)
2135
2136 ## Summarize ModuleAutoGen objects of all modules to be built for this platform
2137 def _GetModuleAutoGenList(self):
2138 if self._ModuleAutoGenList is None:
2139 self._GetAutoGenObjectList()
2140 return self._ModuleAutoGenList
2141
2142 ## Summarize ModuleAutoGen objects of all libraries to be built for this platform
2143 def _GetLibraryAutoGenList(self):
2144 if self._LibraryAutoGenList is None:
2145 self._GetAutoGenObjectList()
2146 return self._LibraryAutoGenList
2147
2148 ## Test if a module is supported by the platform
2149 #
2150 # An error will be raised directly if the module or its arch is not supported
2151 # by the platform or current configuration
2152 #
2153 def ValidModule(self, Module):
2154 return Module in self.Platform.Modules or Module in self.Platform.LibraryInstances \
2155 or Module in self._AsBuildModuleList
2156
2157 ## Resolve the library classes in a module to library instances
2158 #
2159 # This method will not only resolve library classes but also sort the library
2160 # instances according to the dependency-ship.
2161 #
2162 # @param Module The module from which the library classes will be resolved
2163 #
2164 # @retval library_list List of library instances sorted
2165 #
2166 def ApplyLibraryInstance(self, Module):
2167 # Cover the case that the binary INF file is list in the FDF file but not DSC file, return empty list directly
2168 if str(Module) not in self.Platform.Modules:
2169 return []
2170
2171 return GetModuleLibInstances(Module,
2172 self.Platform,
2173 self.BuildDatabase,
2174 self.Arch,
2175 self.BuildTarget,
2176 self.ToolChain,
2177 self.MetaFile,
2178 EdkLogger)
2179
2180 ## Override PCD setting (type, value, ...)
2181 #
2182 # @param ToPcd The PCD to be overrided
2183 # @param FromPcd The PCD overrideing from
2184 #
2185 def _OverridePcd(self, ToPcd, FromPcd, Module="", Msg="", Library=""):
2186 #
2187 # in case there's PCDs coming from FDF file, which have no type given.
2188 # at this point, ToPcd.Type has the type found from dependent
2189 # package
2190 #
2191 TokenCName = ToPcd.TokenCName
2192 for PcdItem in GlobalData.MixedPcd:
2193 if (ToPcd.TokenCName, ToPcd.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:
2194 TokenCName = PcdItem[0]
2195 break
2196 if FromPcd is not None:
2197 if ToPcd.Pending and FromPcd.Type:
2198 ToPcd.Type = FromPcd.Type
2199 elif ToPcd.Type and FromPcd.Type\
2200 and ToPcd.Type != FromPcd.Type and ToPcd.Type in FromPcd.Type:
2201 if ToPcd.Type.strip() == TAB_PCDS_DYNAMIC_EX:
2202 ToPcd.Type = FromPcd.Type
2203 elif ToPcd.Type and FromPcd.Type \
2204 and ToPcd.Type != FromPcd.Type:
2205 if Library:
2206 Module = str(Module) + " 's library file (" + str(Library) + ")"
2207 EdkLogger.error("build", OPTION_CONFLICT, "Mismatched PCD type",
2208 ExtraData="%s.%s is used as [%s] in module %s, but as [%s] in %s."\
2209 % (ToPcd.TokenSpaceGuidCName, TokenCName,
2210 ToPcd.Type, Module, FromPcd.Type, Msg),
2211 File=self.MetaFile)
2212
2213 if FromPcd.MaxDatumSize:
2214 ToPcd.MaxDatumSize = FromPcd.MaxDatumSize
2215 ToPcd.MaxSizeUserSet = FromPcd.MaxDatumSize
2216 if FromPcd.DefaultValue:
2217 ToPcd.DefaultValue = FromPcd.DefaultValue
2218 if FromPcd.TokenValue:
2219 ToPcd.TokenValue = FromPcd.TokenValue
2220 if FromPcd.DatumType:
2221 ToPcd.DatumType = FromPcd.DatumType
2222 if FromPcd.SkuInfoList:
2223 ToPcd.SkuInfoList = FromPcd.SkuInfoList
2224 # Add Flexible PCD format parse
2225 if ToPcd.DefaultValue:
2226 try:
2227 ToPcd.DefaultValue = ValueExpressionEx(ToPcd.DefaultValue, ToPcd.DatumType, self._GuidDict)(True)
2228 except BadExpression as Value:
2229 EdkLogger.error('Parser', FORMAT_INVALID, 'PCD [%s.%s] Value "%s", %s' %(ToPcd.TokenSpaceGuidCName, ToPcd.TokenCName, ToPcd.DefaultValue, Value),
2230 File=self.MetaFile)
2231
2232 # check the validation of datum
2233 IsValid, Cause = CheckPcdDatum(ToPcd.DatumType, ToPcd.DefaultValue)
2234 if not IsValid:
2235 EdkLogger.error('build', FORMAT_INVALID, Cause, File=self.MetaFile,
2236 ExtraData="%s.%s" % (ToPcd.TokenSpaceGuidCName, TokenCName))
2237 ToPcd.validateranges = FromPcd.validateranges
2238 ToPcd.validlists = FromPcd.validlists
2239 ToPcd.expressions = FromPcd.expressions
2240
2241 if FromPcd is not None and ToPcd.DatumType == TAB_VOID and not ToPcd.MaxDatumSize:
2242 EdkLogger.debug(EdkLogger.DEBUG_9, "No MaxDatumSize specified for PCD %s.%s" \
2243 % (ToPcd.TokenSpaceGuidCName, TokenCName))
2244 Value = ToPcd.DefaultValue
2245 if not Value:
2246 ToPcd.MaxDatumSize = '1'
2247 elif Value[0] == 'L':
2248 ToPcd.MaxDatumSize = str((len(Value) - 2) * 2)
2249 elif Value[0] == '{':
2250 ToPcd.MaxDatumSize = str(len(Value.split(',')))
2251 else:
2252 ToPcd.MaxDatumSize = str(len(Value) - 1)
2253
2254 # apply default SKU for dynamic PCDS if specified one is not available
2255 if (ToPcd.Type in PCD_DYNAMIC_TYPE_SET or ToPcd.Type in PCD_DYNAMIC_EX_TYPE_SET) \
2256 and not ToPcd.SkuInfoList:
2257 if self.Platform.SkuName in self.Platform.SkuIds:
2258 SkuName = self.Platform.SkuName
2259 else:
2260 SkuName = TAB_DEFAULT
2261 ToPcd.SkuInfoList = {
2262 SkuName : SkuInfoClass(SkuName, self.Platform.SkuIds[SkuName][0], '', '', '', '', '', ToPcd.DefaultValue)
2263 }
2264
2265 ## Apply PCD setting defined platform to a module
2266 #
2267 # @param Module The module from which the PCD setting will be overrided
2268 #
2269 # @retval PCD_list The list PCDs with settings from platform
2270 #
2271 def ApplyPcdSetting(self, Module, Pcds, Library=""):
2272 # for each PCD in module
2273 for Name, Guid in Pcds:
2274 PcdInModule = Pcds[Name, Guid]
2275 # find out the PCD setting in platform
2276 if (Name, Guid) in self.Platform.Pcds:
2277 PcdInPlatform = self.Platform.Pcds[Name, Guid]
2278 else:
2279 PcdInPlatform = None
2280 # then override the settings if any
2281 self._OverridePcd(PcdInModule, PcdInPlatform, Module, Msg="DSC PCD sections", Library=Library)
2282 # resolve the VariableGuid value
2283 for SkuId in PcdInModule.SkuInfoList:
2284 Sku = PcdInModule.SkuInfoList[SkuId]
2285 if Sku.VariableGuid == '': continue
2286 Sku.VariableGuidValue = GuidValue(Sku.VariableGuid, self.PackageList, self.MetaFile.Path)
2287 if Sku.VariableGuidValue is None:
2288 PackageList = "\n\t".join(str(P) for P in self.PackageList)
2289 EdkLogger.error(
2290 'build',
2291 RESOURCE_NOT_AVAILABLE,
2292 "Value of GUID [%s] is not found in" % Sku.VariableGuid,
2293 ExtraData=PackageList + "\n\t(used with %s.%s from module %s)" \
2294 % (Guid, Name, str(Module)),
2295 File=self.MetaFile
2296 )
2297
2298 # override PCD settings with module specific setting
2299 if Module in self.Platform.Modules:
2300 PlatformModule = self.Platform.Modules[str(Module)]
2301 for Key in PlatformModule.Pcds:
2302 Flag = False
2303 if Key in Pcds:
2304 ToPcd = Pcds[Key]
2305 Flag = True
2306 elif Key in GlobalData.MixedPcd:
2307 for PcdItem in GlobalData.MixedPcd[Key]:
2308 if PcdItem in Pcds:
2309 ToPcd = Pcds[PcdItem]
2310 Flag = True
2311 break
2312 if Flag:
2313 self._OverridePcd(ToPcd, PlatformModule.Pcds[Key], Module, Msg="DSC Components Module scoped PCD section", Library=Library)
2314 # use PCD value to calculate the MaxDatumSize when it is not specified
2315 for Name, Guid in Pcds:
2316 Pcd = Pcds[Name, Guid]
2317 if Pcd.DatumType == TAB_VOID and not Pcd.MaxDatumSize:
2318 Pcd.MaxSizeUserSet = None
2319 Value = Pcd.DefaultValue
2320 if not Value:
2321 Pcd.MaxDatumSize = '1'
2322 elif Value[0] == 'L':
2323 Pcd.MaxDatumSize = str((len(Value) - 2) * 2)
2324 elif Value[0] == '{':
2325 Pcd.MaxDatumSize = str(len(Value.split(',')))
2326 else:
2327 Pcd.MaxDatumSize = str(len(Value) - 1)
2328 return Pcds.values()
2329
2330 ## Resolve library names to library modules
2331 #
2332 # (for Edk.x modules)
2333 #
2334 # @param Module The module from which the library names will be resolved
2335 #
2336 # @retval library_list The list of library modules
2337 #
2338 def ResolveLibraryReference(self, Module):
2339 EdkLogger.verbose("")
2340 EdkLogger.verbose("Library instances of module [%s] [%s]:" % (str(Module), self.Arch))
2341 LibraryConsumerList = [Module]
2342
2343 # "CompilerStub" is a must for Edk modules
2344 if Module.Libraries:
2345 Module.Libraries.append("CompilerStub")
2346 LibraryList = []
2347 while len(LibraryConsumerList) > 0:
2348 M = LibraryConsumerList.pop()
2349 for LibraryName in M.Libraries:
2350 Library = self.Platform.LibraryClasses[LibraryName, ':dummy:']
2351 if Library is None:
2352 for Key in self.Platform.LibraryClasses.data:
2353 if LibraryName.upper() == Key.upper():
2354 Library = self.Platform.LibraryClasses[Key, ':dummy:']
2355 break
2356 if Library is None:
2357 EdkLogger.warn("build", "Library [%s] is not found" % LibraryName, File=str(M),
2358 ExtraData="\t%s [%s]" % (str(Module), self.Arch))
2359 continue
2360
2361 if Library not in LibraryList:
2362 LibraryList.append(Library)
2363 LibraryConsumerList.append(Library)
2364 EdkLogger.verbose("\t" + LibraryName + " : " + str(Library) + ' ' + str(type(Library)))
2365 return LibraryList
2366
2367 ## Calculate the priority value of the build option
2368 #
2369 # @param Key Build option definition contain: TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
2370 #
2371 # @retval Value Priority value based on the priority list.
2372 #
2373 def CalculatePriorityValue(self, Key):
2374 Target, ToolChain, Arch, CommandType, Attr = Key.split('_')
2375 PriorityValue = 0x11111
2376 if Target == "*":
2377 PriorityValue &= 0x01111
2378 if ToolChain == "*":
2379 PriorityValue &= 0x10111
2380 if Arch == "*":
2381 PriorityValue &= 0x11011
2382 if CommandType == "*":
2383 PriorityValue &= 0x11101
2384 if Attr == "*":
2385 PriorityValue &= 0x11110
2386
2387 return self.PrioList["0x%0.5x" % PriorityValue]
2388
2389
2390 ## Expand * in build option key
2391 #
2392 # @param Options Options to be expanded
2393 #
2394 # @retval options Options expanded
2395 #
2396 def _ExpandBuildOption(self, Options, ModuleStyle=None):
2397 BuildOptions = {}
2398 FamilyMatch = False
2399 FamilyIsNull = True
2400
2401 OverrideList = {}
2402 #
2403 # Construct a list contain the build options which need override.
2404 #
2405 for Key in Options:
2406 #
2407 # Key[0] -- tool family
2408 # Key[1] -- TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
2409 #
2410 if (Key[0] == self.BuildRuleFamily and
2411 (ModuleStyle is None or len(Key) < 3 or (len(Key) > 2 and Key[2] == ModuleStyle))):
2412 Target, ToolChain, Arch, CommandType, Attr = Key[1].split('_')
2413 if (Target == self.BuildTarget or Target == "*") and\
2414 (ToolChain == self.ToolChain or ToolChain == "*") and\
2415 (Arch == self.Arch or Arch == "*") and\
2416 Options[Key].startswith("="):
2417
2418 if OverrideList.get(Key[1]) is not None:
2419 OverrideList.pop(Key[1])
2420 OverrideList[Key[1]] = Options[Key]
2421
2422 #
2423 # Use the highest priority value.
2424 #
2425 if (len(OverrideList) >= 2):
2426 KeyList = OverrideList.keys()
2427 for Index in range(len(KeyList)):
2428 NowKey = KeyList[Index]
2429 Target1, ToolChain1, Arch1, CommandType1, Attr1 = NowKey.split("_")
2430 for Index1 in range(len(KeyList) - Index - 1):
2431 NextKey = KeyList[Index1 + Index + 1]
2432 #
2433 # Compare two Key, if one is included by another, choose the higher priority one
2434 #
2435 Target2, ToolChain2, Arch2, CommandType2, Attr2 = NextKey.split("_")
2436 if (Target1 == Target2 or Target1 == "*" or Target2 == "*") and\
2437 (ToolChain1 == ToolChain2 or ToolChain1 == "*" or ToolChain2 == "*") and\
2438 (Arch1 == Arch2 or Arch1 == "*" or Arch2 == "*") and\
2439 (CommandType1 == CommandType2 or CommandType1 == "*" or CommandType2 == "*") and\
2440 (Attr1 == Attr2 or Attr1 == "*" or Attr2 == "*"):
2441
2442 if self.CalculatePriorityValue(NowKey) > self.CalculatePriorityValue(NextKey):
2443 if Options.get((self.BuildRuleFamily, NextKey)) is not None:
2444 Options.pop((self.BuildRuleFamily, NextKey))
2445 else:
2446 if Options.get((self.BuildRuleFamily, NowKey)) is not None:
2447 Options.pop((self.BuildRuleFamily, NowKey))
2448
2449 for Key in Options:
2450 if ModuleStyle is not None and len (Key) > 2:
2451 # Check Module style is EDK or EDKII.
2452 # Only append build option for the matched style module.
2453 if ModuleStyle == EDK_NAME and Key[2] != EDK_NAME:
2454 continue
2455 elif ModuleStyle == EDKII_NAME and Key[2] != EDKII_NAME:
2456 continue
2457 Family = Key[0]
2458 Target, Tag, Arch, Tool, Attr = Key[1].split("_")
2459 # if tool chain family doesn't match, skip it
2460 if Tool in self.ToolDefinition and Family != "":
2461 FamilyIsNull = False
2462 if self.ToolDefinition[Tool].get(TAB_TOD_DEFINES_BUILDRULEFAMILY, "") != "":
2463 if Family != self.ToolDefinition[Tool][TAB_TOD_DEFINES_BUILDRULEFAMILY]:
2464 continue
2465 elif Family != self.ToolDefinition[Tool][TAB_TOD_DEFINES_FAMILY]:
2466 continue
2467 FamilyMatch = True
2468 # expand any wildcard
2469 if Target == "*" or Target == self.BuildTarget:
2470 if Tag == "*" or Tag == self.ToolChain:
2471 if Arch == "*" or Arch == self.Arch:
2472 if Tool not in BuildOptions:
2473 BuildOptions[Tool] = {}
2474 if Attr != "FLAGS" or Attr not in BuildOptions[Tool] or Options[Key].startswith('='):
2475 BuildOptions[Tool][Attr] = Options[Key]
2476 else:
2477 # append options for the same tool except PATH
2478 if Attr != 'PATH':
2479 BuildOptions[Tool][Attr] += " " + Options[Key]
2480 else:
2481 BuildOptions[Tool][Attr] = Options[Key]
2482 # Build Option Family has been checked, which need't to be checked again for family.
2483 if FamilyMatch or FamilyIsNull:
2484 return BuildOptions
2485
2486 for Key in Options:
2487 if ModuleStyle is not None and len (Key) > 2:
2488 # Check Module style is EDK or EDKII.
2489 # Only append build option for the matched style module.
2490 if ModuleStyle == EDK_NAME and Key[2] != EDK_NAME:
2491 continue
2492 elif ModuleStyle == EDKII_NAME and Key[2] != EDKII_NAME:
2493 continue
2494 Family = Key[0]
2495 Target, Tag, Arch, Tool, Attr = Key[1].split("_")
2496 # if tool chain family doesn't match, skip it
2497 if Tool not in self.ToolDefinition or Family == "":
2498 continue
2499 # option has been added before
2500 if Family != self.ToolDefinition[Tool][TAB_TOD_DEFINES_FAMILY]:
2501 continue
2502
2503 # expand any wildcard
2504 if Target == "*" or Target == self.BuildTarget:
2505 if Tag == "*" or Tag == self.ToolChain:
2506 if Arch == "*" or Arch == self.Arch:
2507 if Tool not in BuildOptions:
2508 BuildOptions[Tool] = {}
2509 if Attr != "FLAGS" or Attr not in BuildOptions[Tool] or Options[Key].startswith('='):
2510 BuildOptions[Tool][Attr] = Options[Key]
2511 else:
2512 # append options for the same tool except PATH
2513 if Attr != 'PATH':
2514 BuildOptions[Tool][Attr] += " " + Options[Key]
2515 else:
2516 BuildOptions[Tool][Attr] = Options[Key]
2517 return BuildOptions
2518
2519 ## Append build options in platform to a module
2520 #
2521 # @param Module The module to which the build options will be appened
2522 #
2523 # @retval options The options appended with build options in platform
2524 #
2525 def ApplyBuildOption(self, Module):
2526 # Get the different options for the different style module
2527 if Module.AutoGenVersion < 0x00010005:
2528 PlatformOptions = self.EdkBuildOption
2529 ModuleTypeOptions = self.Platform.GetBuildOptionsByModuleType(EDK_NAME, Module.ModuleType)
2530 else:
2531 PlatformOptions = self.EdkIIBuildOption
2532 ModuleTypeOptions = self.Platform.GetBuildOptionsByModuleType(EDKII_NAME, Module.ModuleType)
2533 ModuleTypeOptions = self._ExpandBuildOption(ModuleTypeOptions)
2534 ModuleOptions = self._ExpandBuildOption(Module.BuildOptions)
2535 if Module in self.Platform.Modules:
2536 PlatformModule = self.Platform.Modules[str(Module)]
2537 PlatformModuleOptions = self._ExpandBuildOption(PlatformModule.BuildOptions)
2538 else:
2539 PlatformModuleOptions = {}
2540
2541 BuildRuleOrder = None
2542 for Options in [self.ToolDefinition, ModuleOptions, PlatformOptions, ModuleTypeOptions, PlatformModuleOptions]:
2543 for Tool in Options:
2544 for Attr in Options[Tool]:
2545 if Attr == TAB_TOD_DEFINES_BUILDRULEORDER:
2546 BuildRuleOrder = Options[Tool][Attr]
2547
2548 AllTools = set(ModuleOptions.keys() + PlatformOptions.keys() +
2549 PlatformModuleOptions.keys() + ModuleTypeOptions.keys() +
2550 self.ToolDefinition.keys())
2551 BuildOptions = defaultdict(lambda: defaultdict(str))
2552 for Tool in AllTools:
2553 for Options in [self.ToolDefinition, ModuleOptions, PlatformOptions, ModuleTypeOptions, PlatformModuleOptions]:
2554 if Tool not in Options:
2555 continue
2556 for Attr in Options[Tool]:
2557 #
2558 # Do not generate it in Makefile
2559 #
2560 if Attr == TAB_TOD_DEFINES_BUILDRULEORDER:
2561 continue
2562 Value = Options[Tool][Attr]
2563 # check if override is indicated
2564 if Value.startswith('='):
2565 BuildOptions[Tool][Attr] = mws.handleWsMacro(Value[1:])
2566 else:
2567 if Attr != 'PATH':
2568 BuildOptions[Tool][Attr] += " " + mws.handleWsMacro(Value)
2569 else:
2570 BuildOptions[Tool][Attr] = mws.handleWsMacro(Value)
2571
2572 if Module.AutoGenVersion < 0x00010005 and self.Workspace.UniFlag is not None:
2573 #
2574 # Override UNI flag only for EDK module.
2575 #
2576 BuildOptions['BUILD']['FLAGS'] = self.Workspace.UniFlag
2577 return BuildOptions, BuildRuleOrder
2578
2579 Platform = property(_GetPlatform)
2580 Name = property(_GetName)
2581 Guid = property(_GetGuid)
2582 Version = property(_GetVersion)
2583
2584 OutputDir = property(_GetOutputDir)
2585 BuildDir = property(_GetBuildDir)
2586 MakeFileDir = property(_GetMakeFileDir)
2587 FdfFile = property(_GetFdfFile)
2588
2589 PcdTokenNumber = property(_GetPcdTokenNumbers) # (TokenCName, TokenSpaceGuidCName) : GeneratedTokenNumber
2590 DynamicPcdList = property(_GetDynamicPcdList) # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
2591 NonDynamicPcdList = property(_GetNonDynamicPcdList) # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
2592 NonDynamicPcdDict = property(_GetNonDynamicPcdDict)
2593 PackageList = property(_GetPackageList)
2594
2595 ToolDefinition = property(_GetToolDefinition) # toolcode : tool path
2596 ToolDefinitionFile = property(_GetToolDefFile) # toolcode : lib path
2597 ToolChainFamily = property(_GetToolChainFamily)
2598 BuildRuleFamily = property(_GetBuildRuleFamily)
2599 BuildOption = property(_GetBuildOptions) # toolcode : option
2600 EdkBuildOption = property(_GetEdkBuildOptions) # edktoolcode : option
2601 EdkIIBuildOption = property(_GetEdkIIBuildOptions) # edkiitoolcode : option
2602
2603 BuildCommand = property(_GetBuildCommand)
2604 BuildRule = property(_GetBuildRule)
2605 ModuleAutoGenList = property(_GetModuleAutoGenList)
2606 LibraryAutoGenList = property(_GetLibraryAutoGenList)
2607 GenFdsCommand = property(_GenFdsCommand)
2608
2609 #
2610 # extend lists contained in a dictionary with lists stored in another dictionary
2611 # if CopyToDict is not derived from DefaultDict(list) then this may raise exception
2612 #
2613 def ExtendCopyDictionaryLists(CopyToDict, CopyFromDict):
2614 for Key in CopyFromDict:
2615 CopyToDict[Key].extend(CopyFromDict[Key])
2616
2617
2618 ## ModuleAutoGen class
2619 #
2620 # This class encapsules the AutoGen behaviors for the build tools. In addition to
2621 # the generation of AutoGen.h and AutoGen.c, it will generate *.depex file according
2622 # to the [depex] section in module's inf file.
2623 #
2624 class ModuleAutoGen(AutoGen):
2625 # call super().__init__ then call the worker function with different parameter count
2626 def __init__(self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):
2627 try:
2628 self._Init
2629 except:
2630 super(ModuleAutoGen, self).__init__(Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)
2631 self._InitWorker(Workspace, MetaFile, Target, Toolchain, Arch, *args)
2632 self._Init = True
2633
2634 ## Cache the timestamps of metafiles of every module in a class variable
2635 #
2636 TimeDict = {}
2637
2638 def __new__(cls, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):
2639 obj = super(ModuleAutoGen, cls).__new__(cls, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)
2640 # check if this module is employed by active platform
2641 if not PlatformAutoGen(Workspace, args[0], Target, Toolchain, Arch).ValidModule(MetaFile):
2642 EdkLogger.verbose("Module [%s] for [%s] is not employed by active platform\n" \
2643 % (MetaFile, Arch))
2644 return None
2645 return obj
2646
2647 ## Initialize ModuleAutoGen
2648 #
2649 # @param Workspace EdkIIWorkspaceBuild object
2650 # @param ModuleFile The path of module file
2651 # @param Target Build target (DEBUG, RELEASE)
2652 # @param Toolchain Name of tool chain
2653 # @param Arch The arch the module supports
2654 # @param PlatformFile Platform meta-file
2655 #
2656 def _InitWorker(self, Workspace, ModuleFile, Target, Toolchain, Arch, PlatformFile):
2657 EdkLogger.debug(EdkLogger.DEBUG_9, "AutoGen module [%s] [%s]" % (ModuleFile, Arch))
2658 GlobalData.gProcessingFile = "%s [%s, %s, %s]" % (ModuleFile, Arch, Toolchain, Target)
2659
2660 self.Workspace = Workspace
2661 self.WorkspaceDir = Workspace.WorkspaceDir
2662 self._GuidDict = Workspace._GuidDict
2663 self.MetaFile = ModuleFile
2664 self.PlatformInfo = PlatformAutoGen(Workspace, PlatformFile, Target, Toolchain, Arch)
2665
2666 self.SourceDir = self.MetaFile.SubDir
2667 self.SourceDir = mws.relpath(self.SourceDir, self.WorkspaceDir)
2668
2669 self.SourceOverrideDir = None
2670 # use overrided path defined in DSC file
2671 if self.MetaFile.Key in GlobalData.gOverrideDir:
2672 self.SourceOverrideDir = GlobalData.gOverrideDir[self.MetaFile.Key]
2673
2674 self.ToolChain = Toolchain
2675 self.BuildTarget = Target
2676 self.Arch = Arch
2677 self.ToolChainFamily = self.PlatformInfo.ToolChainFamily
2678 self.BuildRuleFamily = self.PlatformInfo.BuildRuleFamily
2679
2680 self.IsMakeFileCreated = False
2681 self.IsCodeFileCreated = False
2682 self.IsAsBuiltInfCreated = False
2683 self.DepexGenerated = False
2684
2685 self.BuildDatabase = self.Workspace.BuildDatabase
2686 self.BuildRuleOrder = None
2687 self.BuildTime = 0
2688