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