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