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