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