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