]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/AutoGen/AutoGen.py
BaseTools: Fix a bug for VpdOffset calculate
[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 DscTimeStamp = self.Platform.MetaFile.TimeStamp
1260 FvPath = os.path.join(self.BuildDir, "FV")
1261 if not os.path.exists(FvPath):
1262 try:
1263 os.makedirs(FvPath)
1264 except:
1265 EdkLogger.error("build", FILE_WRITE_FAILURE, "Fail to create FV folder under %s" % self.BuildDir)
1266
1267
1268 VpdFilePath = os.path.join(FvPath, "%s.txt" % self.Platform.VpdToolGuid)
1269
1270
1271 if not os.path.exists(VpdFilePath) or os.path.getmtime(VpdFilePath) < DscTimeStamp:
1272 VpdFile.Write(VpdFilePath)
1273
1274 # retrieve BPDG tool's path from tool_def.txt according to VPD_TOOL_GUID defined in DSC file.
1275 BPDGToolName = None
1276 for ToolDef in self.ToolDefinition.values():
1277 if ToolDef.has_key("GUID") and ToolDef["GUID"] == self.Platform.VpdToolGuid:
1278 if not ToolDef.has_key("PATH"):
1279 EdkLogger.error("build", ATTRIBUTE_NOT_AVAILABLE, "PATH attribute was not provided for BPDG guid tool %s in tools_def.txt" % self.Platform.VpdToolGuid)
1280 BPDGToolName = ToolDef["PATH"]
1281 break
1282 # Call third party GUID BPDG tool.
1283 if BPDGToolName != None:
1284 VpdInfoFile.CallExtenalBPDGTool(BPDGToolName, VpdFilePath)
1285 else:
1286 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.")
1287
1288 # Process VPD map file generated by third party BPDG tool
1289 if NeedProcessVpdMapFile:
1290 VpdMapFilePath = os.path.join(self.BuildDir, "FV", "%s.map" % self.Platform.VpdToolGuid)
1291 if os.path.exists(VpdMapFilePath):
1292 VpdFile.Read(VpdMapFilePath)
1293
1294 # Fixup "*" offset
1295 for Pcd in self._DynamicPcdList:
1296 # just pick the a value to determine whether is unicode string type
1297 i = 0
1298 for (SkuName,Sku) in Pcd.SkuInfoList.items():
1299 if Sku.VpdOffset == "*":
1300 Sku.VpdOffset = VpdFile.GetOffset(Pcd)[i].strip()
1301 i += 1
1302 else:
1303 EdkLogger.error("build", FILE_READ_FAILURE, "Can not find VPD map file %s to fix up VPD offset." % VpdMapFilePath)
1304
1305 # Delete the DynamicPcdList At the last time enter into this function
1306 del self._DynamicPcdList[:]
1307 self._DynamicPcdList.extend(UnicodePcdArray)
1308 self._DynamicPcdList.extend(HiiPcdArray)
1309 self._DynamicPcdList.extend(OtherPcdArray)
1310 self.AllPcdList = self._NonDynamicPcdList + self._DynamicPcdList
1311
1312 ## Return the platform build data object
1313 def _GetPlatform(self):
1314 if self._Platform == None:
1315 self._Platform = self.BuildDatabase[self.MetaFile, self.Arch, self.BuildTarget, self.ToolChain]
1316 return self._Platform
1317
1318 ## Return platform name
1319 def _GetName(self):
1320 return self.Platform.PlatformName
1321
1322 ## Return the meta file GUID
1323 def _GetGuid(self):
1324 return self.Platform.Guid
1325
1326 ## Return the platform version
1327 def _GetVersion(self):
1328 return self.Platform.Version
1329
1330 ## Return the FDF file name
1331 def _GetFdfFile(self):
1332 if self._FdfFile == None:
1333 if self.Workspace.FdfFile != "":
1334 self._FdfFile= mws.join(self.WorkspaceDir, self.Workspace.FdfFile)
1335 else:
1336 self._FdfFile = ''
1337 return self._FdfFile
1338
1339 ## Return the build output directory platform specifies
1340 def _GetOutputDir(self):
1341 return self.Platform.OutputDirectory
1342
1343 ## Return the directory to store all intermediate and final files built
1344 def _GetBuildDir(self):
1345 if self._BuildDir == None:
1346 if os.path.isabs(self.OutputDir):
1347 self._BuildDir = path.join(
1348 path.abspath(self.OutputDir),
1349 self.BuildTarget + "_" + self.ToolChain,
1350 )
1351 else:
1352 self._BuildDir = path.join(
1353 self.WorkspaceDir,
1354 self.OutputDir,
1355 self.BuildTarget + "_" + self.ToolChain,
1356 )
1357 return self._BuildDir
1358
1359 ## Return directory of platform makefile
1360 #
1361 # @retval string Makefile directory
1362 #
1363 def _GetMakeFileDir(self):
1364 if self._MakeFileDir == None:
1365 self._MakeFileDir = path.join(self.BuildDir, self.Arch)
1366 return self._MakeFileDir
1367
1368 ## Return build command string
1369 #
1370 # @retval string Build command string
1371 #
1372 def _GetBuildCommand(self):
1373 if self._BuildCommand == None:
1374 self._BuildCommand = []
1375 if "MAKE" in self.ToolDefinition and "PATH" in self.ToolDefinition["MAKE"]:
1376 self._BuildCommand += SplitOption(self.ToolDefinition["MAKE"]["PATH"])
1377 if "FLAGS" in self.ToolDefinition["MAKE"]:
1378 NewOption = self.ToolDefinition["MAKE"]["FLAGS"].strip()
1379 if NewOption != '':
1380 self._BuildCommand += SplitOption(NewOption)
1381 return self._BuildCommand
1382
1383 ## Get tool chain definition
1384 #
1385 # Get each tool defition for given tool chain from tools_def.txt and platform
1386 #
1387 def _GetToolDefinition(self):
1388 if self._ToolDefinitions == None:
1389 ToolDefinition = self.Workspace.ToolDef.ToolsDefTxtDictionary
1390 if TAB_TOD_DEFINES_COMMAND_TYPE not in self.Workspace.ToolDef.ToolsDefTxtDatabase:
1391 EdkLogger.error('build', RESOURCE_NOT_AVAILABLE, "No tools found in configuration",
1392 ExtraData="[%s]" % self.MetaFile)
1393 self._ToolDefinitions = {}
1394 DllPathList = set()
1395 for Def in ToolDefinition:
1396 Target, Tag, Arch, Tool, Attr = Def.split("_")
1397 if Target != self.BuildTarget or Tag != self.ToolChain or Arch != self.Arch:
1398 continue
1399
1400 Value = ToolDefinition[Def]
1401 # don't record the DLL
1402 if Attr == "DLL":
1403 DllPathList.add(Value)
1404 continue
1405
1406 if Tool not in self._ToolDefinitions:
1407 self._ToolDefinitions[Tool] = {}
1408 self._ToolDefinitions[Tool][Attr] = Value
1409
1410 ToolsDef = ''
1411 MakePath = ''
1412 if GlobalData.gOptions.SilentMode and "MAKE" in self._ToolDefinitions:
1413 if "FLAGS" not in self._ToolDefinitions["MAKE"]:
1414 self._ToolDefinitions["MAKE"]["FLAGS"] = ""
1415 self._ToolDefinitions["MAKE"]["FLAGS"] += " -s"
1416 MakeFlags = ''
1417 for Tool in self._ToolDefinitions:
1418 for Attr in self._ToolDefinitions[Tool]:
1419 Value = self._ToolDefinitions[Tool][Attr]
1420 if Tool in self.BuildOption and Attr in self.BuildOption[Tool]:
1421 # check if override is indicated
1422 if self.BuildOption[Tool][Attr].startswith('='):
1423 Value = self.BuildOption[Tool][Attr][1:]
1424 else:
1425 Value += " " + self.BuildOption[Tool][Attr]
1426
1427 if Attr == "PATH":
1428 # Don't put MAKE definition in the file
1429 if Tool == "MAKE":
1430 MakePath = Value
1431 else:
1432 ToolsDef += "%s = %s\n" % (Tool, Value)
1433 elif Attr != "DLL":
1434 # Don't put MAKE definition in the file
1435 if Tool == "MAKE":
1436 if Attr == "FLAGS":
1437 MakeFlags = Value
1438 else:
1439 ToolsDef += "%s_%s = %s\n" % (Tool, Attr, Value)
1440 ToolsDef += "\n"
1441
1442 SaveFileOnChange(self.ToolDefinitionFile, ToolsDef)
1443 for DllPath in DllPathList:
1444 os.environ["PATH"] = DllPath + os.pathsep + os.environ["PATH"]
1445 os.environ["MAKE_FLAGS"] = MakeFlags
1446
1447 return self._ToolDefinitions
1448
1449 ## Return the paths of tools
1450 def _GetToolDefFile(self):
1451 if self._ToolDefFile == None:
1452 self._ToolDefFile = os.path.join(self.MakeFileDir, "TOOLS_DEF." + self.Arch)
1453 return self._ToolDefFile
1454
1455 ## Retrieve the toolchain family of given toolchain tag. Default to 'MSFT'.
1456 def _GetToolChainFamily(self):
1457 if self._ToolChainFamily == None:
1458 ToolDefinition = self.Workspace.ToolDef.ToolsDefTxtDatabase
1459 if TAB_TOD_DEFINES_FAMILY not in ToolDefinition \
1460 or self.ToolChain not in ToolDefinition[TAB_TOD_DEFINES_FAMILY] \
1461 or not ToolDefinition[TAB_TOD_DEFINES_FAMILY][self.ToolChain]:
1462 EdkLogger.verbose("No tool chain family found in configuration for %s. Default to MSFT." \
1463 % self.ToolChain)
1464 self._ToolChainFamily = "MSFT"
1465 else:
1466 self._ToolChainFamily = ToolDefinition[TAB_TOD_DEFINES_FAMILY][self.ToolChain]
1467 return self._ToolChainFamily
1468
1469 def _GetBuildRuleFamily(self):
1470 if self._BuildRuleFamily == None:
1471 ToolDefinition = self.Workspace.ToolDef.ToolsDefTxtDatabase
1472 if TAB_TOD_DEFINES_BUILDRULEFAMILY not in ToolDefinition \
1473 or self.ToolChain not in ToolDefinition[TAB_TOD_DEFINES_BUILDRULEFAMILY] \
1474 or not ToolDefinition[TAB_TOD_DEFINES_BUILDRULEFAMILY][self.ToolChain]:
1475 EdkLogger.verbose("No tool chain family found in configuration for %s. Default to MSFT." \
1476 % self.ToolChain)
1477 self._BuildRuleFamily = "MSFT"
1478 else:
1479 self._BuildRuleFamily = ToolDefinition[TAB_TOD_DEFINES_BUILDRULEFAMILY][self.ToolChain]
1480 return self._BuildRuleFamily
1481
1482 ## Return the build options specific for all modules in this platform
1483 def _GetBuildOptions(self):
1484 if self._BuildOption == None:
1485 self._BuildOption = self._ExpandBuildOption(self.Platform.BuildOptions)
1486 return self._BuildOption
1487
1488 ## Return the build options specific for EDK modules in this platform
1489 def _GetEdkBuildOptions(self):
1490 if self._EdkBuildOption == None:
1491 self._EdkBuildOption = self._ExpandBuildOption(self.Platform.BuildOptions, EDK_NAME)
1492 return self._EdkBuildOption
1493
1494 ## Return the build options specific for EDKII modules in this platform
1495 def _GetEdkIIBuildOptions(self):
1496 if self._EdkIIBuildOption == None:
1497 self._EdkIIBuildOption = self._ExpandBuildOption(self.Platform.BuildOptions, EDKII_NAME)
1498 return self._EdkIIBuildOption
1499
1500 ## Parse build_rule.txt in Conf Directory.
1501 #
1502 # @retval BuildRule object
1503 #
1504 def _GetBuildRule(self):
1505 if self._BuildRule == None:
1506 BuildRuleFile = None
1507 if TAB_TAT_DEFINES_BUILD_RULE_CONF in self.Workspace.TargetTxt.TargetTxtDictionary:
1508 BuildRuleFile = self.Workspace.TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_BUILD_RULE_CONF]
1509 if BuildRuleFile in [None, '']:
1510 BuildRuleFile = gDefaultBuildRuleFile
1511 self._BuildRule = BuildRule(BuildRuleFile)
1512 if self._BuildRule._FileVersion == "":
1513 self._BuildRule._FileVersion = AutoGenReqBuildRuleVerNum
1514 else:
1515 if self._BuildRule._FileVersion < AutoGenReqBuildRuleVerNum :
1516 # If Build Rule's version is less than the version number required by the tools, halting the build.
1517 EdkLogger.error("build", AUTOGEN_ERROR,
1518 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])"\
1519 % (self._BuildRule._FileVersion, AutoGenReqBuildRuleVerNum))
1520
1521 return self._BuildRule
1522
1523 ## Summarize the packages used by modules in this platform
1524 def _GetPackageList(self):
1525 if self._PackageList == None:
1526 self._PackageList = set()
1527 for La in self.LibraryAutoGenList:
1528 self._PackageList.update(La.DependentPackageList)
1529 for Ma in self.ModuleAutoGenList:
1530 self._PackageList.update(Ma.DependentPackageList)
1531 #Collect package set information from INF of FDF
1532 PkgSet = set()
1533 for ModuleFile in self._AsBuildModuleList:
1534 if ModuleFile in self.Platform.Modules:
1535 continue
1536 ModuleData = self.BuildDatabase[ModuleFile, self.Arch, self.BuildTarget, self.ToolChain]
1537 PkgSet.update(ModuleData.Packages)
1538 self._PackageList = list(self._PackageList) + list (PkgSet)
1539 return self._PackageList
1540
1541 def _GetNonDynamicPcdDict(self):
1542 if self._NonDynamicPcdDict:
1543 return self._NonDynamicPcdDict
1544 for Pcd in self.NonDynamicPcdList:
1545 self._NonDynamicPcdDict[(Pcd.TokenCName,Pcd.TokenSpaceGuidCName)] = Pcd
1546 return self._NonDynamicPcdDict
1547
1548 ## Get list of non-dynamic PCDs
1549 def _GetNonDynamicPcdList(self):
1550 if self._NonDynamicPcdList == None:
1551 self.CollectPlatformDynamicPcds()
1552 return self._NonDynamicPcdList
1553
1554 ## Get list of dynamic PCDs
1555 def _GetDynamicPcdList(self):
1556 if self._DynamicPcdList == None:
1557 self.CollectPlatformDynamicPcds()
1558 return self._DynamicPcdList
1559
1560 ## Generate Token Number for all PCD
1561 def _GetPcdTokenNumbers(self):
1562 if self._PcdTokenNumber == None:
1563 self._PcdTokenNumber = sdict()
1564 TokenNumber = 1
1565 #
1566 # Make the Dynamic and DynamicEx PCD use within different TokenNumber area.
1567 # Such as:
1568 #
1569 # Dynamic PCD:
1570 # TokenNumber 0 ~ 10
1571 # DynamicEx PCD:
1572 # TokeNumber 11 ~ 20
1573 #
1574 for Pcd in self.DynamicPcdList:
1575 if Pcd.Phase == "PEI":
1576 if Pcd.Type in ["Dynamic", "DynamicDefault", "DynamicVpd", "DynamicHii"]:
1577 EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))
1578 self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber
1579 TokenNumber += 1
1580
1581 for Pcd in self.DynamicPcdList:
1582 if Pcd.Phase == "PEI":
1583 if Pcd.Type in ["DynamicEx", "DynamicExDefault", "DynamicExVpd", "DynamicExHii"]:
1584 EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))
1585 self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber
1586 TokenNumber += 1
1587
1588 for Pcd in self.DynamicPcdList:
1589 if Pcd.Phase == "DXE":
1590 if Pcd.Type in ["Dynamic", "DynamicDefault", "DynamicVpd", "DynamicHii"]:
1591 EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))
1592 self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber
1593 TokenNumber += 1
1594
1595 for Pcd in self.DynamicPcdList:
1596 if Pcd.Phase == "DXE":
1597 if Pcd.Type in ["DynamicEx", "DynamicExDefault", "DynamicExVpd", "DynamicExHii"]:
1598 EdkLogger.debug(EdkLogger.DEBUG_5, "%s %s (%s) -> %d" % (Pcd.TokenCName, Pcd.TokenSpaceGuidCName, Pcd.Phase, TokenNumber))
1599 self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber
1600 TokenNumber += 1
1601
1602 for Pcd in self.NonDynamicPcdList:
1603 self._PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName] = TokenNumber
1604 TokenNumber += 1
1605 return self._PcdTokenNumber
1606
1607 ## Summarize ModuleAutoGen objects of all modules/libraries to be built for this platform
1608 def _GetAutoGenObjectList(self):
1609 self._ModuleAutoGenList = []
1610 self._LibraryAutoGenList = []
1611 for ModuleFile in self.Platform.Modules:
1612 Ma = ModuleAutoGen(
1613 self.Workspace,
1614 ModuleFile,
1615 self.BuildTarget,
1616 self.ToolChain,
1617 self.Arch,
1618 self.MetaFile
1619 )
1620 if Ma not in self._ModuleAutoGenList:
1621 self._ModuleAutoGenList.append(Ma)
1622 for La in Ma.LibraryAutoGenList:
1623 if La not in self._LibraryAutoGenList:
1624 self._LibraryAutoGenList.append(La)
1625 if Ma not in La._ReferenceModules:
1626 La._ReferenceModules.append(Ma)
1627
1628 ## Summarize ModuleAutoGen objects of all modules to be built for this platform
1629 def _GetModuleAutoGenList(self):
1630 if self._ModuleAutoGenList == None:
1631 self._GetAutoGenObjectList()
1632 return self._ModuleAutoGenList
1633
1634 ## Summarize ModuleAutoGen objects of all libraries to be built for this platform
1635 def _GetLibraryAutoGenList(self):
1636 if self._LibraryAutoGenList == None:
1637 self._GetAutoGenObjectList()
1638 return self._LibraryAutoGenList
1639
1640 ## Test if a module is supported by the platform
1641 #
1642 # An error will be raised directly if the module or its arch is not supported
1643 # by the platform or current configuration
1644 #
1645 def ValidModule(self, Module):
1646 return Module in self.Platform.Modules or Module in self.Platform.LibraryInstances \
1647 or Module in self._AsBuildModuleList
1648
1649 ## Resolve the library classes in a module to library instances
1650 #
1651 # This method will not only resolve library classes but also sort the library
1652 # instances according to the dependency-ship.
1653 #
1654 # @param Module The module from which the library classes will be resolved
1655 #
1656 # @retval library_list List of library instances sorted
1657 #
1658 def ApplyLibraryInstance(self, Module):
1659 ModuleType = Module.ModuleType
1660
1661 # for overridding library instances with module specific setting
1662 PlatformModule = self.Platform.Modules[str(Module)]
1663
1664 # add forced library instances (specified under LibraryClasses sections)
1665 #
1666 # If a module has a MODULE_TYPE of USER_DEFINED,
1667 # do not link in NULL library class instances from the global [LibraryClasses.*] sections.
1668 #
1669 if Module.ModuleType != SUP_MODULE_USER_DEFINED:
1670 for LibraryClass in self.Platform.LibraryClasses.GetKeys():
1671 if LibraryClass.startswith("NULL") and self.Platform.LibraryClasses[LibraryClass, Module.ModuleType]:
1672 Module.LibraryClasses[LibraryClass] = self.Platform.LibraryClasses[LibraryClass, Module.ModuleType]
1673
1674 # add forced library instances (specified in module overrides)
1675 for LibraryClass in PlatformModule.LibraryClasses:
1676 if LibraryClass.startswith("NULL"):
1677 Module.LibraryClasses[LibraryClass] = PlatformModule.LibraryClasses[LibraryClass]
1678
1679 # EdkII module
1680 LibraryConsumerList = [Module]
1681 Constructor = []
1682 ConsumedByList = sdict()
1683 LibraryInstance = sdict()
1684
1685 EdkLogger.verbose("")
1686 EdkLogger.verbose("Library instances of module [%s] [%s]:" % (str(Module), self.Arch))
1687 while len(LibraryConsumerList) > 0:
1688 M = LibraryConsumerList.pop()
1689 for LibraryClassName in M.LibraryClasses:
1690 if LibraryClassName not in LibraryInstance:
1691 # override library instance for this module
1692 if LibraryClassName in PlatformModule.LibraryClasses:
1693 LibraryPath = PlatformModule.LibraryClasses[LibraryClassName]
1694 else:
1695 LibraryPath = self.Platform.LibraryClasses[LibraryClassName, ModuleType]
1696 if LibraryPath == None or LibraryPath == "":
1697 LibraryPath = M.LibraryClasses[LibraryClassName]
1698 if LibraryPath == None or LibraryPath == "":
1699 EdkLogger.error("build", RESOURCE_NOT_AVAILABLE,
1700 "Instance of library class [%s] is not found" % LibraryClassName,
1701 File=self.MetaFile,
1702 ExtraData="in [%s] [%s]\n\tconsumed by module [%s]" % (str(M), self.Arch, str(Module)))
1703
1704 LibraryModule = self.BuildDatabase[LibraryPath, self.Arch, self.BuildTarget, self.ToolChain]
1705 # for those forced library instance (NULL library), add a fake library class
1706 if LibraryClassName.startswith("NULL"):
1707 LibraryModule.LibraryClass.append(LibraryClassObject(LibraryClassName, [ModuleType]))
1708 elif LibraryModule.LibraryClass == None \
1709 or len(LibraryModule.LibraryClass) == 0 \
1710 or (ModuleType != 'USER_DEFINED'
1711 and ModuleType not in LibraryModule.LibraryClass[0].SupModList):
1712 # only USER_DEFINED can link against any library instance despite of its SupModList
1713 EdkLogger.error("build", OPTION_MISSING,
1714 "Module type [%s] is not supported by library instance [%s]" \
1715 % (ModuleType, LibraryPath), File=self.MetaFile,
1716 ExtraData="consumed by [%s]" % str(Module))
1717
1718 LibraryInstance[LibraryClassName] = LibraryModule
1719 LibraryConsumerList.append(LibraryModule)
1720 EdkLogger.verbose("\t" + str(LibraryClassName) + " : " + str(LibraryModule))
1721 else:
1722 LibraryModule = LibraryInstance[LibraryClassName]
1723
1724 if LibraryModule == None:
1725 continue
1726
1727 if LibraryModule.ConstructorList != [] and LibraryModule not in Constructor:
1728 Constructor.append(LibraryModule)
1729
1730 if LibraryModule not in ConsumedByList:
1731 ConsumedByList[LibraryModule] = []
1732 # don't add current module itself to consumer list
1733 if M != Module:
1734 if M in ConsumedByList[LibraryModule]:
1735 continue
1736 ConsumedByList[LibraryModule].append(M)
1737 #
1738 # Initialize the sorted output list to the empty set
1739 #
1740 SortedLibraryList = []
1741 #
1742 # Q <- Set of all nodes with no incoming edges
1743 #
1744 LibraryList = [] #LibraryInstance.values()
1745 Q = []
1746 for LibraryClassName in LibraryInstance:
1747 M = LibraryInstance[LibraryClassName]
1748 LibraryList.append(M)
1749 if ConsumedByList[M] == []:
1750 Q.append(M)
1751
1752 #
1753 # start the DAG algorithm
1754 #
1755 while True:
1756 EdgeRemoved = True
1757 while Q == [] and EdgeRemoved:
1758 EdgeRemoved = False
1759 # for each node Item with a Constructor
1760 for Item in LibraryList:
1761 if Item not in Constructor:
1762 continue
1763 # for each Node without a constructor with an edge e from Item to Node
1764 for Node in ConsumedByList[Item]:
1765 if Node in Constructor:
1766 continue
1767 # remove edge e from the graph if Node has no constructor
1768 ConsumedByList[Item].remove(Node)
1769 EdgeRemoved = True
1770 if ConsumedByList[Item] == []:
1771 # insert Item into Q
1772 Q.insert(0, Item)
1773 break
1774 if Q != []:
1775 break
1776 # DAG is done if there's no more incoming edge for all nodes
1777 if Q == []:
1778 break
1779
1780 # remove node from Q
1781 Node = Q.pop()
1782 # output Node
1783 SortedLibraryList.append(Node)
1784
1785 # for each node Item with an edge e from Node to Item do
1786 for Item in LibraryList:
1787 if Node not in ConsumedByList[Item]:
1788 continue
1789 # remove edge e from the graph
1790 ConsumedByList[Item].remove(Node)
1791
1792 if ConsumedByList[Item] != []:
1793 continue
1794 # insert Item into Q, if Item has no other incoming edges
1795 Q.insert(0, Item)
1796
1797 #
1798 # if any remaining node Item in the graph has a constructor and an incoming edge, then the graph has a cycle
1799 #
1800 for Item in LibraryList:
1801 if ConsumedByList[Item] != [] and Item in Constructor and len(Constructor) > 1:
1802 ErrorMessage = "\tconsumed by " + "\n\tconsumed by ".join([str(L) for L in ConsumedByList[Item]])
1803 EdkLogger.error("build", BUILD_ERROR, 'Library [%s] with constructors has a cycle' % str(Item),
1804 ExtraData=ErrorMessage, File=self.MetaFile)
1805 if Item not in SortedLibraryList:
1806 SortedLibraryList.append(Item)
1807
1808 #
1809 # Build the list of constructor and destructir names
1810 # The DAG Topo sort produces the destructor order, so the list of constructors must generated in the reverse order
1811 #
1812 SortedLibraryList.reverse()
1813 return SortedLibraryList
1814
1815
1816 ## Override PCD setting (type, value, ...)
1817 #
1818 # @param ToPcd The PCD to be overrided
1819 # @param FromPcd The PCD overrideing from
1820 #
1821 def _OverridePcd(self, ToPcd, FromPcd, Module=""):
1822 #
1823 # in case there's PCDs coming from FDF file, which have no type given.
1824 # at this point, ToPcd.Type has the type found from dependent
1825 # package
1826 #
1827 if FromPcd != None:
1828 if ToPcd.Pending and FromPcd.Type not in [None, '']:
1829 ToPcd.Type = FromPcd.Type
1830 elif (ToPcd.Type not in [None, '']) and (FromPcd.Type not in [None, ''])\
1831 and (ToPcd.Type != FromPcd.Type) and (ToPcd.Type in FromPcd.Type):
1832 if ToPcd.Type.strip() == "DynamicEx":
1833 ToPcd.Type = FromPcd.Type
1834 elif ToPcd.Type not in [None, ''] and FromPcd.Type not in [None, ''] \
1835 and ToPcd.Type != FromPcd.Type:
1836 EdkLogger.error("build", OPTION_CONFLICT, "Mismatched PCD type",
1837 ExtraData="%s.%s is defined as [%s] in module %s, but as [%s] in platform."\
1838 % (ToPcd.TokenSpaceGuidCName, ToPcd.TokenCName,
1839 ToPcd.Type, Module, FromPcd.Type),
1840 File=self.MetaFile)
1841
1842 if FromPcd.MaxDatumSize not in [None, '']:
1843 ToPcd.MaxDatumSize = FromPcd.MaxDatumSize
1844 if FromPcd.DefaultValue not in [None, '']:
1845 ToPcd.DefaultValue = FromPcd.DefaultValue
1846 if FromPcd.TokenValue not in [None, '']:
1847 ToPcd.TokenValue = FromPcd.TokenValue
1848 if FromPcd.MaxDatumSize not in [None, '']:
1849 ToPcd.MaxDatumSize = FromPcd.MaxDatumSize
1850 if FromPcd.DatumType not in [None, '']:
1851 ToPcd.DatumType = FromPcd.DatumType
1852 if FromPcd.SkuInfoList not in [None, '', []]:
1853 ToPcd.SkuInfoList = FromPcd.SkuInfoList
1854
1855 # check the validation of datum
1856 IsValid, Cause = CheckPcdDatum(ToPcd.DatumType, ToPcd.DefaultValue)
1857 if not IsValid:
1858 EdkLogger.error('build', FORMAT_INVALID, Cause, File=self.MetaFile,
1859 ExtraData="%s.%s" % (ToPcd.TokenSpaceGuidCName, ToPcd.TokenCName))
1860 ToPcd.validateranges = FromPcd.validateranges
1861 ToPcd.validlists = FromPcd.validlists
1862 ToPcd.expressions = FromPcd.expressions
1863
1864 if ToPcd.DatumType == "VOID*" and ToPcd.MaxDatumSize in ['', None]:
1865 EdkLogger.debug(EdkLogger.DEBUG_9, "No MaxDatumSize specified for PCD %s.%s" \
1866 % (ToPcd.TokenSpaceGuidCName, ToPcd.TokenCName))
1867 Value = ToPcd.DefaultValue
1868 if Value in [None, '']:
1869 ToPcd.MaxDatumSize = '1'
1870 elif Value[0] == 'L':
1871 ToPcd.MaxDatumSize = str((len(Value) - 2) * 2)
1872 elif Value[0] == '{':
1873 ToPcd.MaxDatumSize = str(len(Value.split(',')))
1874 else:
1875 ToPcd.MaxDatumSize = str(len(Value) - 1)
1876
1877 # apply default SKU for dynamic PCDS if specified one is not available
1878 if (ToPcd.Type in PCD_DYNAMIC_TYPE_LIST or ToPcd.Type in PCD_DYNAMIC_EX_TYPE_LIST) \
1879 and ToPcd.SkuInfoList in [None, {}, '']:
1880 if self.Platform.SkuName in self.Platform.SkuIds:
1881 SkuName = self.Platform.SkuName
1882 else:
1883 SkuName = 'DEFAULT'
1884 ToPcd.SkuInfoList = {
1885 SkuName : SkuInfoClass(SkuName, self.Platform.SkuIds[SkuName], '', '', '', '', '', ToPcd.DefaultValue)
1886 }
1887
1888 ## Apply PCD setting defined platform to a module
1889 #
1890 # @param Module The module from which the PCD setting will be overrided
1891 #
1892 # @retval PCD_list The list PCDs with settings from platform
1893 #
1894 def ApplyPcdSetting(self, Module, Pcds):
1895 # for each PCD in module
1896 for Name, Guid in Pcds:
1897 PcdInModule = Pcds[Name, Guid]
1898 # find out the PCD setting in platform
1899 if (Name, Guid) in self.Platform.Pcds:
1900 PcdInPlatform = self.Platform.Pcds[Name, Guid]
1901 else:
1902 PcdInPlatform = None
1903 # then override the settings if any
1904 self._OverridePcd(PcdInModule, PcdInPlatform, Module)
1905 # resolve the VariableGuid value
1906 for SkuId in PcdInModule.SkuInfoList:
1907 Sku = PcdInModule.SkuInfoList[SkuId]
1908 if Sku.VariableGuid == '': continue
1909 Sku.VariableGuidValue = GuidValue(Sku.VariableGuid, self.PackageList)
1910 if Sku.VariableGuidValue == None:
1911 PackageList = "\n\t".join([str(P) for P in self.PackageList])
1912 EdkLogger.error(
1913 'build',
1914 RESOURCE_NOT_AVAILABLE,
1915 "Value of GUID [%s] is not found in" % Sku.VariableGuid,
1916 ExtraData=PackageList + "\n\t(used with %s.%s from module %s)" \
1917 % (Guid, Name, str(Module)),
1918 File=self.MetaFile
1919 )
1920
1921 # override PCD settings with module specific setting
1922 if Module in self.Platform.Modules:
1923 PlatformModule = self.Platform.Modules[str(Module)]
1924 for Key in PlatformModule.Pcds:
1925 if Key in Pcds:
1926 self._OverridePcd(Pcds[Key], PlatformModule.Pcds[Key], Module)
1927 return Pcds.values()
1928
1929 ## Resolve library names to library modules
1930 #
1931 # (for Edk.x modules)
1932 #
1933 # @param Module The module from which the library names will be resolved
1934 #
1935 # @retval library_list The list of library modules
1936 #
1937 def ResolveLibraryReference(self, Module):
1938 EdkLogger.verbose("")
1939 EdkLogger.verbose("Library instances of module [%s] [%s]:" % (str(Module), self.Arch))
1940 LibraryConsumerList = [Module]
1941
1942 # "CompilerStub" is a must for Edk modules
1943 if Module.Libraries:
1944 Module.Libraries.append("CompilerStub")
1945 LibraryList = []
1946 while len(LibraryConsumerList) > 0:
1947 M = LibraryConsumerList.pop()
1948 for LibraryName in M.Libraries:
1949 Library = self.Platform.LibraryClasses[LibraryName, ':dummy:']
1950 if Library == None:
1951 for Key in self.Platform.LibraryClasses.data.keys():
1952 if LibraryName.upper() == Key.upper():
1953 Library = self.Platform.LibraryClasses[Key, ':dummy:']
1954 break
1955 if Library == None:
1956 EdkLogger.warn("build", "Library [%s] is not found" % LibraryName, File=str(M),
1957 ExtraData="\t%s [%s]" % (str(Module), self.Arch))
1958 continue
1959
1960 if Library not in LibraryList:
1961 LibraryList.append(Library)
1962 LibraryConsumerList.append(Library)
1963 EdkLogger.verbose("\t" + LibraryName + " : " + str(Library) + ' ' + str(type(Library)))
1964 return LibraryList
1965
1966 ## Calculate the priority value of the build option
1967 #
1968 # @param Key Build option definition contain: TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
1969 #
1970 # @retval Value Priority value based on the priority list.
1971 #
1972 def CalculatePriorityValue(self, Key):
1973 Target, ToolChain, Arch, CommandType, Attr = Key.split('_')
1974 PriorityValue = 0x11111
1975 if Target == "*":
1976 PriorityValue &= 0x01111
1977 if ToolChain == "*":
1978 PriorityValue &= 0x10111
1979 if Arch == "*":
1980 PriorityValue &= 0x11011
1981 if CommandType == "*":
1982 PriorityValue &= 0x11101
1983 if Attr == "*":
1984 PriorityValue &= 0x11110
1985
1986 return self.PrioList["0x%0.5x" % PriorityValue]
1987
1988
1989 ## Expand * in build option key
1990 #
1991 # @param Options Options to be expanded
1992 #
1993 # @retval options Options expanded
1994 #
1995 def _ExpandBuildOption(self, Options, ModuleStyle=None):
1996 BuildOptions = {}
1997 FamilyMatch = False
1998 FamilyIsNull = True
1999
2000 OverrideList = {}
2001 #
2002 # Construct a list contain the build options which need override.
2003 #
2004 for Key in Options:
2005 #
2006 # Key[0] -- tool family
2007 # Key[1] -- TARGET_TOOLCHAIN_ARCH_COMMANDTYPE_ATTRIBUTE
2008 #
2009 if (Key[0] == self.BuildRuleFamily and
2010 (ModuleStyle == None or len(Key) < 3 or (len(Key) > 2 and Key[2] == ModuleStyle))):
2011 Target, ToolChain, Arch, CommandType, Attr = Key[1].split('_')
2012 if Target == self.BuildTarget or Target == "*":
2013 if ToolChain == self.ToolChain or ToolChain == "*":
2014 if Arch == self.Arch or Arch == "*":
2015 if Options[Key].startswith("="):
2016 if OverrideList.get(Key[1]) != None:
2017 OverrideList.pop(Key[1])
2018 OverrideList[Key[1]] = Options[Key]
2019
2020 #
2021 # Use the highest priority value.
2022 #
2023 if (len(OverrideList) >= 2):
2024 KeyList = OverrideList.keys()
2025 for Index in range(len(KeyList)):
2026 NowKey = KeyList[Index]
2027 Target1, ToolChain1, Arch1, CommandType1, Attr1 = NowKey.split("_")
2028 for Index1 in range(len(KeyList) - Index - 1):
2029 NextKey = KeyList[Index1 + Index + 1]
2030 #
2031 # Compare two Key, if one is included by another, choose the higher priority one
2032 #
2033 Target2, ToolChain2, Arch2, CommandType2, Attr2 = NextKey.split("_")
2034 if Target1 == Target2 or Target1 == "*" or Target2 == "*":
2035 if ToolChain1 == ToolChain2 or ToolChain1 == "*" or ToolChain2 == "*":
2036 if Arch1 == Arch2 or Arch1 == "*" or Arch2 == "*":
2037 if CommandType1 == CommandType2 or CommandType1 == "*" or CommandType2 == "*":
2038 if Attr1 == Attr2 or Attr1 == "*" or Attr2 == "*":
2039 if self.CalculatePriorityValue(NowKey) > self.CalculatePriorityValue(NextKey):
2040 if Options.get((self.BuildRuleFamily, NextKey)) != None:
2041 Options.pop((self.BuildRuleFamily, NextKey))
2042 else:
2043 if Options.get((self.BuildRuleFamily, NowKey)) != None:
2044 Options.pop((self.BuildRuleFamily, NowKey))
2045
2046 for Key in Options:
2047 if ModuleStyle != None and len (Key) > 2:
2048 # Check Module style is EDK or EDKII.
2049 # Only append build option for the matched style module.
2050 if ModuleStyle == EDK_NAME and Key[2] != EDK_NAME:
2051 continue
2052 elif ModuleStyle == EDKII_NAME and Key[2] != EDKII_NAME:
2053 continue
2054 Family = Key[0]
2055 Target, Tag, Arch, Tool, Attr = Key[1].split("_")
2056 # if tool chain family doesn't match, skip it
2057 if Tool in self.ToolDefinition and Family != "":
2058 FamilyIsNull = False
2059 if self.ToolDefinition[Tool].get(TAB_TOD_DEFINES_BUILDRULEFAMILY, "") != "":
2060 if Family != self.ToolDefinition[Tool][TAB_TOD_DEFINES_BUILDRULEFAMILY]:
2061 continue
2062 elif Family != self.ToolDefinition[Tool][TAB_TOD_DEFINES_FAMILY]:
2063 continue
2064 FamilyMatch = True
2065 # expand any wildcard
2066 if Target == "*" or Target == self.BuildTarget:
2067 if Tag == "*" or Tag == self.ToolChain:
2068 if Arch == "*" or Arch == self.Arch:
2069 if Tool not in BuildOptions:
2070 BuildOptions[Tool] = {}
2071 if Attr != "FLAGS" or Attr not in BuildOptions[Tool] or Options[Key].startswith('='):
2072 BuildOptions[Tool][Attr] = Options[Key]
2073 else:
2074 # append options for the same tool
2075 BuildOptions[Tool][Attr] += " " + Options[Key]
2076 # Build Option Family has been checked, which need't to be checked again for family.
2077 if FamilyMatch or FamilyIsNull:
2078 return BuildOptions
2079
2080 for Key in Options:
2081 if ModuleStyle != None and len (Key) > 2:
2082 # Check Module style is EDK or EDKII.
2083 # Only append build option for the matched style module.
2084 if ModuleStyle == EDK_NAME and Key[2] != EDK_NAME:
2085 continue
2086 elif ModuleStyle == EDKII_NAME and Key[2] != EDKII_NAME:
2087 continue
2088 Family = Key[0]
2089 Target, Tag, Arch, Tool, Attr = Key[1].split("_")
2090 # if tool chain family doesn't match, skip it
2091 if Tool not in self.ToolDefinition or Family == "":
2092 continue
2093 # option has been added before
2094 if Family != self.ToolDefinition[Tool][TAB_TOD_DEFINES_FAMILY]:
2095 continue
2096
2097 # expand any wildcard
2098 if Target == "*" or Target == self.BuildTarget:
2099 if Tag == "*" or Tag == self.ToolChain:
2100 if Arch == "*" or Arch == self.Arch:
2101 if Tool not in BuildOptions:
2102 BuildOptions[Tool] = {}
2103 if Attr != "FLAGS" or Attr not in BuildOptions[Tool] or Options[Key].startswith('='):
2104 BuildOptions[Tool][Attr] = Options[Key]
2105 else:
2106 # append options for the same tool
2107 BuildOptions[Tool][Attr] += " " + Options[Key]
2108 return BuildOptions
2109
2110 ## Append build options in platform to a module
2111 #
2112 # @param Module The module to which the build options will be appened
2113 #
2114 # @retval options The options appended with build options in platform
2115 #
2116 def ApplyBuildOption(self, Module):
2117 # Get the different options for the different style module
2118 if Module.AutoGenVersion < 0x00010005:
2119 PlatformOptions = self.EdkBuildOption
2120 ModuleTypeOptions = self.Platform.GetBuildOptionsByModuleType(EDK_NAME, Module.ModuleType)
2121 else:
2122 PlatformOptions = self.EdkIIBuildOption
2123 ModuleTypeOptions = self.Platform.GetBuildOptionsByModuleType(EDKII_NAME, Module.ModuleType)
2124 ModuleTypeOptions = self._ExpandBuildOption(ModuleTypeOptions)
2125 ModuleOptions = self._ExpandBuildOption(Module.BuildOptions)
2126 if Module in self.Platform.Modules:
2127 PlatformModule = self.Platform.Modules[str(Module)]
2128 PlatformModuleOptions = self._ExpandBuildOption(PlatformModule.BuildOptions)
2129 else:
2130 PlatformModuleOptions = {}
2131
2132 BuildRuleOrder = None
2133 for Options in [self.ToolDefinition, ModuleOptions, PlatformOptions, ModuleTypeOptions, PlatformModuleOptions]:
2134 for Tool in Options:
2135 for Attr in Options[Tool]:
2136 if Attr == TAB_TOD_DEFINES_BUILDRULEORDER:
2137 BuildRuleOrder = Options[Tool][Attr]
2138
2139 AllTools = set(ModuleOptions.keys() + PlatformOptions.keys() +
2140 PlatformModuleOptions.keys() + ModuleTypeOptions.keys() +
2141 self.ToolDefinition.keys())
2142 BuildOptions = {}
2143 for Tool in AllTools:
2144 if Tool not in BuildOptions:
2145 BuildOptions[Tool] = {}
2146
2147 for Options in [self.ToolDefinition, ModuleOptions, PlatformOptions, ModuleTypeOptions, PlatformModuleOptions]:
2148 if Tool not in Options:
2149 continue
2150 for Attr in Options[Tool]:
2151 Value = Options[Tool][Attr]
2152 #
2153 # Do not generate it in Makefile
2154 #
2155 if Attr == TAB_TOD_DEFINES_BUILDRULEORDER:
2156 continue
2157 if Attr not in BuildOptions[Tool]:
2158 BuildOptions[Tool][Attr] = ""
2159 # check if override is indicated
2160 if Value.startswith('='):
2161 ToolPath = Value[1:]
2162 ToolPath = mws.handleWsMacro(ToolPath)
2163 BuildOptions[Tool][Attr] = ToolPath
2164 else:
2165 Value = mws.handleWsMacro(Value)
2166 BuildOptions[Tool][Attr] += " " + Value
2167 if Module.AutoGenVersion < 0x00010005 and self.Workspace.UniFlag != None:
2168 #
2169 # Override UNI flag only for EDK module.
2170 #
2171 if 'BUILD' not in BuildOptions:
2172 BuildOptions['BUILD'] = {}
2173 BuildOptions['BUILD']['FLAGS'] = self.Workspace.UniFlag
2174 return BuildOptions, BuildRuleOrder
2175
2176 Platform = property(_GetPlatform)
2177 Name = property(_GetName)
2178 Guid = property(_GetGuid)
2179 Version = property(_GetVersion)
2180
2181 OutputDir = property(_GetOutputDir)
2182 BuildDir = property(_GetBuildDir)
2183 MakeFileDir = property(_GetMakeFileDir)
2184 FdfFile = property(_GetFdfFile)
2185
2186 PcdTokenNumber = property(_GetPcdTokenNumbers) # (TokenCName, TokenSpaceGuidCName) : GeneratedTokenNumber
2187 DynamicPcdList = property(_GetDynamicPcdList) # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
2188 NonDynamicPcdList = property(_GetNonDynamicPcdList) # [(TokenCName1, TokenSpaceGuidCName1), (TokenCName2, TokenSpaceGuidCName2), ...]
2189 NonDynamicPcdDict = property(_GetNonDynamicPcdDict)
2190 PackageList = property(_GetPackageList)
2191
2192 ToolDefinition = property(_GetToolDefinition) # toolcode : tool path
2193 ToolDefinitionFile = property(_GetToolDefFile) # toolcode : lib path
2194 ToolChainFamily = property(_GetToolChainFamily)
2195 BuildRuleFamily = property(_GetBuildRuleFamily)
2196 BuildOption = property(_GetBuildOptions) # toolcode : option
2197 EdkBuildOption = property(_GetEdkBuildOptions) # edktoolcode : option
2198 EdkIIBuildOption = property(_GetEdkIIBuildOptions) # edkiitoolcode : option
2199
2200 BuildCommand = property(_GetBuildCommand)
2201 BuildRule = property(_GetBuildRule)
2202 ModuleAutoGenList = property(_GetModuleAutoGenList)
2203 LibraryAutoGenList = property(_GetLibraryAutoGenList)
2204 GenFdsCommand = property(_GenFdsCommand)
2205
2206 ## ModuleAutoGen class
2207 #
2208 # This class encapsules the AutoGen behaviors for the build tools. In addition to
2209 # the generation of AutoGen.h and AutoGen.c, it will generate *.depex file according
2210 # to the [depex] section in module's inf file.
2211 #
2212 class ModuleAutoGen(AutoGen):
2213 ## The real constructor of ModuleAutoGen
2214 #
2215 # This method is not supposed to be called by users of ModuleAutoGen. It's
2216 # only used by factory method __new__() to do real initialization work for an
2217 # object of ModuleAutoGen
2218 #
2219 # @param Workspace EdkIIWorkspaceBuild object
2220 # @param ModuleFile The path of module file
2221 # @param Target Build target (DEBUG, RELEASE)
2222 # @param Toolchain Name of tool chain
2223 # @param Arch The arch the module supports
2224 # @param PlatformFile Platform meta-file
2225 #
2226 def _Init(self, Workspace, ModuleFile, Target, Toolchain, Arch, PlatformFile):
2227 EdkLogger.debug(EdkLogger.DEBUG_9, "AutoGen module [%s] [%s]" % (ModuleFile, Arch))
2228 GlobalData.gProcessingFile = "%s [%s, %s, %s]" % (ModuleFile, Arch, Toolchain, Target)
2229
2230 self.Workspace = Workspace
2231 self.WorkspaceDir = Workspace.WorkspaceDir
2232
2233 self.MetaFile = ModuleFile
2234 self.PlatformInfo = PlatformAutoGen(Workspace, PlatformFile, Target, Toolchain, Arch)
2235 # check if this module is employed by active platform
2236 if not self.PlatformInfo.ValidModule(self.MetaFile):
2237 EdkLogger.verbose("Module [%s] for [%s] is not employed by active platform\n" \
2238 % (self.MetaFile, Arch))
2239 return False
2240
2241 self.SourceDir = self.MetaFile.SubDir
2242 self.SourceDir = mws.relpath(self.SourceDir, self.WorkspaceDir)
2243
2244 self.SourceOverrideDir = None
2245 # use overrided path defined in DSC file
2246 if self.MetaFile.Key in GlobalData.gOverrideDir:
2247 self.SourceOverrideDir = GlobalData.gOverrideDir[self.MetaFile.Key]
2248
2249 self.ToolChain = Toolchain
2250 self.BuildTarget = Target
2251 self.Arch = Arch
2252 self.ToolChainFamily = self.PlatformInfo.ToolChainFamily
2253 self.BuildRuleFamily = self.PlatformInfo.BuildRuleFamily
2254
2255 self.IsMakeFileCreated = False
2256 self.IsCodeFileCreated = False
2257 self.IsAsBuiltInfCreated = False
2258 self.DepexGenerated = False
2259
2260 self.BuildDatabase = self.Workspace.BuildDatabase
2261 self.BuildRuleOrder = None
2262
2263 self._Module = None
2264 self._Name = None
2265 self._Guid = None
2266 self._Version = None
2267 self._ModuleType = None
2268 self._ComponentType = None
2269 self._PcdIsDriver = None
2270 self._AutoGenVersion = None
2271 self._LibraryFlag = None
2272 self._CustomMakefile = None
2273 self._Macro = None
2274
2275 self._BuildDir = None
2276 self._OutputDir = None
2277 self._DebugDir = None
2278 self._MakeFileDir = None
2279
2280 self._IncludePathList = None
2281 self._AutoGenFileList = None
2282 self._UnicodeFileList = None
2283 self._SourceFileList = None
2284 self._ObjectFileList = None
2285 self._BinaryFileList = None
2286
2287 self._DependentPackageList = None
2288 self._DependentLibraryList = None
2289 self._LibraryAutoGenList = None
2290 self._DerivedPackageList = None
2291 self._ModulePcdList = None
2292 self._LibraryPcdList = None
2293 self._PcdComments = sdict()
2294 self._GuidList = None
2295 self._GuidsUsedByPcd = None
2296 self._GuidComments = sdict()
2297 self._ProtocolList = None
2298 self._ProtocolComments = sdict()
2299 self._PpiList = None
2300 self._PpiComments = sdict()
2301 self._DepexList = None
2302 self._DepexExpressionList = None
2303 self._BuildOption = None
2304 self._BuildOptionIncPathList = None
2305 self._BuildTargets = None
2306 self._IntroBuildTargetList = None
2307 self._FinalBuildTargetList = None
2308 self._FileTypes = None
2309 self._BuildRules = None
2310
2311 ## The Modules referenced to this Library
2312 # Only Library has this attribute
2313 self._ReferenceModules = []
2314
2315 ## Store the FixedAtBuild Pcds
2316 #
2317 self._FixedAtBuildPcds = []
2318 self.ConstPcd = {}
2319 return True
2320
2321 def __repr__(self):
2322 return "%s [%s]" % (self.MetaFile, self.Arch)
2323
2324 # Get FixedAtBuild Pcds of this Module
2325 def _GetFixedAtBuildPcds(self):
2326 if self._FixedAtBuildPcds:
2327 return self._FixedAtBuildPcds
2328 for Pcd in self.ModulePcdList:
2329 if self.IsLibrary:
2330 if not (Pcd.Pending == False and Pcd.Type == "FixedAtBuild"):
2331 continue
2332 elif Pcd.Type != "FixedAtBuild":
2333 continue
2334 if Pcd not in self._FixedAtBuildPcds:
2335 self._FixedAtBuildPcds.append(Pcd)
2336
2337 return self._FixedAtBuildPcds
2338
2339 def _GetUniqueBaseName(self):
2340 BaseName = self.Name
2341 for Module in self.PlatformInfo.ModuleAutoGenList:
2342 if Module.MetaFile == self.MetaFile:
2343 continue
2344 if Module.Name == self.Name:
2345 if uuid.UUID(Module.Guid) == uuid.UUID(self.Guid):
2346 EdkLogger.error("build", FILE_DUPLICATED, 'Modules have same BaseName and FILE_GUID:\n'
2347 ' %s\n %s' % (Module.MetaFile, self.MetaFile))
2348 BaseName = '%s_%s' % (self.Name, self.Guid)
2349 return BaseName
2350
2351 # Macros could be used in build_rule.txt (also Makefile)
2352 def _GetMacros(self):
2353 if self._Macro == None:
2354 self._Macro = sdict()
2355 self._Macro["WORKSPACE" ] = self.WorkspaceDir
2356 self._Macro["MODULE_NAME" ] = self.Name
2357 self._Macro["MODULE_NAME_GUID" ] = self._GetUniqueBaseName()
2358 self._Macro["MODULE_GUID" ] = self.Guid
2359 self._Macro["MODULE_VERSION" ] = self.Version
2360 self._Macro["MODULE_TYPE" ] = self.ModuleType
2361 self._Macro["MODULE_FILE" ] = str(self.MetaFile)
2362 self._Macro["MODULE_FILE_BASE_NAME" ] = self.MetaFile.BaseName
2363 self._Macro["MODULE_RELATIVE_DIR" ] = self.SourceDir
2364 self._Macro["MODULE_DIR" ] = self.SourceDir
2365
2366 self._Macro["BASE_NAME" ] = self.Name
2367
2368 self._Macro["ARCH" ] = self.Arch
2369 self._Macro["TOOLCHAIN" ] = self.ToolChain
2370 self._Macro["TOOLCHAIN_TAG" ] = self.ToolChain
2371 self._Macro["TOOL_CHAIN_TAG" ] = self.ToolChain
2372 self._Macro["TARGET" ] = self.BuildTarget
2373
2374 self._Macro["BUILD_DIR" ] = self.PlatformInfo.BuildDir
2375 self._Macro["BIN_DIR" ] = os.path.join(self.PlatformInfo.BuildDir, self.Arch)
2376 self._Macro["LIB_DIR" ] = os.path.join(self.PlatformInfo.BuildDir, self.Arch)
2377 self._Macro["MODULE_BUILD_DIR" ] = self.BuildDir
2378 self._Macro["OUTPUT_DIR" ] = self.OutputDir
2379 self._Macro["DEBUG_DIR" ] = self.DebugDir
2380 return self._Macro
2381
2382 ## Return the module build data object
2383 def _GetModule(self):
2384 if self._Module == None:
2385 self._Module = self.Workspace.BuildDatabase[self.MetaFile, self.Arch, self.BuildTarget, self.ToolChain]
2386 return self._Module
2387
2388 ## Return the module name
2389 def _GetBaseName(self):
2390 return self.Module.BaseName
2391
2392 ## Return the module DxsFile if exist
2393 def _GetDxsFile(self):
2394 return self.Module.DxsFile
2395
2396 ## Return the module SourceOverridePath
2397 def _GetSourceOverridePath(self):
2398 return self.Module.SourceOverridePath
2399
2400 ## Return the module meta-file GUID
2401 def _GetGuid(self):
2402 #
2403 # To build same module more than once, the module path with FILE_GUID overridden has
2404 # the file name FILE_GUIDmodule.inf, but the relative path (self.MetaFile.File) is the realy path
2405 # in DSC. The overridden GUID can be retrieved from file name
2406 #
2407 if os.path.basename(self.MetaFile.File) != os.path.basename(self.MetaFile.Path):
2408 #
2409 # Length of GUID is 36
2410 #
2411 return os.path.basename(self.MetaFile.Path)[:36]
2412 return self.Module.Guid
2413
2414 ## Return the module version
2415 def _GetVersion(self):
2416 return self.Module.Version
2417
2418 ## Return the module type
2419 def _GetModuleType(self):
2420 return self.Module.ModuleType
2421
2422 ## Return the component type (for Edk.x style of module)
2423 def _GetComponentType(self):
2424 return self.Module.ComponentType
2425
2426 ## Return the build type
2427 def _GetBuildType(self):
2428 return self.Module.BuildType
2429
2430 ## Return the PCD_IS_DRIVER setting
2431 def _GetPcdIsDriver(self):
2432 return self.Module.PcdIsDriver
2433
2434 ## Return the autogen version, i.e. module meta-file version
2435 def _GetAutoGenVersion(self):
2436 return self.Module.AutoGenVersion
2437
2438 ## Check if the module is library or not
2439 def _IsLibrary(self):
2440 if self._LibraryFlag == None:
2441 if self.Module.LibraryClass != None and self.Module.LibraryClass != []:
2442 self._LibraryFlag = True
2443 else:
2444 self._LibraryFlag = False
2445 return self._LibraryFlag
2446
2447 ## Check if the module is binary module or not
2448 def _IsBinaryModule(self):
2449 return self.Module.IsBinaryModule
2450
2451 ## Return the directory to store intermediate files of the module
2452 def _GetBuildDir(self):
2453 if self._BuildDir == None:
2454 self._BuildDir = path.join(
2455 self.PlatformInfo.BuildDir,
2456 self.Arch,
2457 self.SourceDir,
2458 self.MetaFile.BaseName
2459 )
2460 CreateDirectory(self._BuildDir)
2461 return self._BuildDir
2462
2463 ## Return the directory to store the intermediate object files of the mdoule
2464 def _GetOutputDir(self):
2465 if self._OutputDir == None:
2466 self._OutputDir = path.join(self.BuildDir, "OUTPUT")
2467 CreateDirectory(self._OutputDir)
2468 return self._OutputDir
2469
2470 ## Return the directory to store auto-gened source files of the mdoule
2471 def _GetDebugDir(self):
2472 if self._DebugDir == None:
2473 self._DebugDir = path.join(self.BuildDir, "DEBUG")
2474 CreateDirectory(self._DebugDir)
2475 return self._DebugDir
2476
2477 ## Return the path of custom file
2478 def _GetCustomMakefile(self):
2479 if self._CustomMakefile == None:
2480 self._CustomMakefile = {}
2481 for Type in self.Module.CustomMakefile:
2482 if Type in gMakeTypeMap:
2483 MakeType = gMakeTypeMap[Type]
2484 else:
2485 MakeType = 'nmake'
2486 if self.SourceOverrideDir != None:
2487 File = os.path.join(self.SourceOverrideDir, self.Module.CustomMakefile[Type])
2488 if not os.path.exists(File):
2489 File = os.path.join(self.SourceDir, self.Module.CustomMakefile[Type])
2490 else:
2491 File = os.path.join(self.SourceDir, self.Module.CustomMakefile[Type])
2492 self._CustomMakefile[MakeType] = File
2493 return self._CustomMakefile
2494
2495 ## Return the directory of the makefile
2496 #
2497 # @retval string The directory string of module's makefile
2498 #
2499 def _GetMakeFileDir(self):
2500 return self.BuildDir
2501
2502 ## Return build command string
2503 #
2504 # @retval string Build command string
2505 #
2506 def _GetBuildCommand(self):
2507 return self.PlatformInfo.BuildCommand
2508
2509 ## Get object list of all packages the module and its dependent libraries belong to
2510 #
2511 # @retval list The list of package object
2512 #
2513 def _GetDerivedPackageList(self):
2514 PackageList = []
2515 for M in [self.Module] + self.DependentLibraryList:
2516 for Package in M.Packages:
2517 if Package in PackageList:
2518 continue
2519 PackageList.append(Package)
2520 return PackageList
2521
2522 ## Get the depex string
2523 #
2524 # @return : a string contain all depex expresion.
2525 def _GetDepexExpresionString(self):
2526 DepexStr = ''
2527 DepexList = []
2528 ## DPX_SOURCE IN Define section.
2529 if self.Module.DxsFile:
2530 return DepexStr
2531 for M in [self.Module] + self.DependentLibraryList:
2532 Filename = M.MetaFile.Path
2533 InfObj = InfSectionParser.InfSectionParser(Filename)
2534 DepexExpresionList = InfObj.GetDepexExpresionList()
2535 for DepexExpresion in DepexExpresionList:
2536 for key in DepexExpresion.keys():
2537 Arch, ModuleType = key
2538 # the type of build module is USER_DEFINED.
2539 # All different DEPEX section tags would be copied into the As Built INF file
2540 # and there would be separate DEPEX section tags
2541 if self.ModuleType.upper() == SUP_MODULE_USER_DEFINED:
2542 if (Arch.upper() == self.Arch.upper()) and (ModuleType.upper() != TAB_ARCH_COMMON):
2543 DepexList.append({(Arch, ModuleType): DepexExpresion[key][:]})
2544 else:
2545 if Arch.upper() == TAB_ARCH_COMMON or \
2546 (Arch.upper() == self.Arch.upper() and \
2547 ModuleType.upper() in [TAB_ARCH_COMMON, self.ModuleType.upper()]):
2548 DepexList.append({(Arch, ModuleType): DepexExpresion[key][:]})
2549
2550 #the type of build module is USER_DEFINED.
2551 if self.ModuleType.upper() == SUP_MODULE_USER_DEFINED:
2552 for Depex in DepexList:
2553 for key in Depex.keys():
2554 DepexStr += '[Depex.%s.%s]\n' % key
2555 DepexStr += '\n'.join(['# '+ val for val in Depex[key]])
2556 DepexStr += '\n\n'
2557 if not DepexStr:
2558 return '[Depex.%s]\n' % self.Arch
2559 return DepexStr
2560
2561 #the type of build module not is USER_DEFINED.
2562 Count = 0
2563 for Depex in DepexList:
2564 Count += 1
2565 if DepexStr != '':
2566 DepexStr += ' AND '
2567 DepexStr += '('
2568 for D in Depex.values():
2569 DepexStr += ' '.join([val for val in D])
2570 Index = DepexStr.find('END')
2571 if Index > -1 and Index == len(DepexStr) - 3:
2572 DepexStr = DepexStr[:-3]
2573 DepexStr = DepexStr.strip()
2574 DepexStr += ')'
2575 if Count == 1:
2576 DepexStr = DepexStr.lstrip('(').rstrip(')').strip()
2577 if not DepexStr:
2578 return '[Depex.%s]\n' % self.Arch
2579 return '[Depex.%s]\n# ' % self.Arch + DepexStr
2580
2581 ## Merge dependency expression
2582 #
2583 # @retval list The token list of the dependency expression after parsed
2584 #
2585 def _GetDepexTokenList(self):
2586 if self._DepexList == None:
2587 self._DepexList = {}
2588 if self.DxsFile or self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:
2589 return self._DepexList
2590
2591 self._DepexList[self.ModuleType] = []
2592
2593 for ModuleType in self._DepexList:
2594 DepexList = self._DepexList[ModuleType]
2595 #
2596 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion
2597 #
2598 for M in [self.Module] + self.DependentLibraryList:
2599 Inherited = False
2600 for D in M.Depex[self.Arch, ModuleType]:
2601 if DepexList != []:
2602 DepexList.append('AND')
2603 DepexList.append('(')
2604 DepexList.extend(D)
2605 if DepexList[-1] == 'END': # no need of a END at this time
2606 DepexList.pop()
2607 DepexList.append(')')
2608 Inherited = True
2609 if Inherited:
2610 EdkLogger.verbose("DEPEX[%s] (+%s) = %s" % (self.Name, M.BaseName, DepexList))
2611 if 'BEFORE' in DepexList or 'AFTER' in DepexList:
2612 break
2613 if len(DepexList) > 0:
2614 EdkLogger.verbose('')
2615 return self._DepexList
2616
2617 ## Merge dependency expression
2618 #
2619 # @retval list The token list of the dependency expression after parsed
2620 #
2621 def _GetDepexExpressionTokenList(self):
2622 if self._DepexExpressionList == None:
2623 self._DepexExpressionList = {}
2624 if self.DxsFile or self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:
2625 return self._DepexExpressionList
2626
2627 self._DepexExpressionList[self.ModuleType] = ''
2628
2629 for ModuleType in self._DepexExpressionList:
2630 DepexExpressionList = self._DepexExpressionList[ModuleType]
2631 #
2632 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion
2633 #
2634 for M in [self.Module] + self.DependentLibraryList:
2635 Inherited = False
2636 for D in M.DepexExpression[self.Arch, ModuleType]:
2637 if DepexExpressionList != '':
2638 DepexExpressionList += ' AND '
2639 DepexExpressionList += '('
2640 DepexExpressionList += D
2641 DepexExpressionList = DepexExpressionList.rstrip('END').strip()
2642 DepexExpressionList += ')'
2643 Inherited = True
2644 if Inherited:
2645 EdkLogger.verbose("DEPEX[%s] (+%s) = %s" % (self.Name, M.BaseName, DepexExpressionList))
2646 if 'BEFORE' in DepexExpressionList or 'AFTER' in DepexExpressionList:
2647 break
2648 if len(DepexExpressionList) > 0:
2649 EdkLogger.verbose('')
2650 self._DepexExpressionList[ModuleType] = DepexExpressionList
2651 return self._DepexExpressionList
2652
2653 ## Return the list of specification version required for the module
2654 #
2655 # @retval list The list of specification defined in module file
2656 #
2657 def _GetSpecification(self):
2658 return self.Module.Specification
2659
2660 ## Tool option for the module build
2661 #
2662 # @param PlatformInfo The object of PlatformBuildInfo
2663 # @retval dict The dict containing valid options
2664 #
2665 def _GetModuleBuildOption(self):
2666 if self._BuildOption == None:
2667 self._BuildOption, self.BuildRuleOrder = self.PlatformInfo.ApplyBuildOption(self.Module)
2668 if self.BuildRuleOrder:
2669 self.BuildRuleOrder = ['.%s' % Ext for Ext in self.BuildRuleOrder.split()]
2670 return self._BuildOption
2671
2672 ## Get include path list from tool option for the module build
2673 #
2674 # @retval list The include path list
2675 #
2676 def _GetBuildOptionIncPathList(self):
2677 if self._BuildOptionIncPathList == None:
2678 #
2679 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT
2680 # is the former use /I , the Latter used -I to specify include directories
2681 #
2682 if self.PlatformInfo.ToolChainFamily in ('MSFT'):
2683 gBuildOptIncludePattern = re.compile(r"(?:.*?)/I[ \t]*([^ ]*)", re.MULTILINE | re.DOTALL)
2684 elif self.PlatformInfo.ToolChainFamily in ('INTEL', 'GCC', 'RVCT'):
2685 gBuildOptIncludePattern = re.compile(r"(?:.*?)-I[ \t]*([^ ]*)", re.MULTILINE | re.DOTALL)
2686 else:
2687 #
2688 # New ToolChainFamily, don't known whether there is option to specify include directories
2689 #
2690 self._BuildOptionIncPathList = []
2691 return self._BuildOptionIncPathList
2692
2693 BuildOptionIncPathList = []
2694 for Tool in ('CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'ASM'):
2695 Attr = 'FLAGS'
2696 try:
2697 FlagOption = self.BuildOption[Tool][Attr]
2698 except KeyError:
2699 FlagOption = ''
2700
2701 if self.PlatformInfo.ToolChainFamily != 'RVCT':
2702 IncPathList = [NormPath(Path, self.Macros) for Path in gBuildOptIncludePattern.findall(FlagOption)]
2703 else:
2704 #
2705 # RVCT may specify a list of directory seperated by commas
2706 #
2707 IncPathList = []
2708 for Path in gBuildOptIncludePattern.findall(FlagOption):
2709 PathList = GetSplitList(Path, TAB_COMMA_SPLIT)
2710 IncPathList += [NormPath(PathEntry, self.Macros) for PathEntry in PathList]
2711
2712 #
2713 # EDK II modules must not reference header files outside of the packages they depend on or
2714 # within the module's directory tree. Report error if violation.
2715 #
2716 if self.AutoGenVersion >= 0x00010005 and len(IncPathList) > 0:
2717 for Path in IncPathList:
2718 if (Path not in self.IncludePathList) and (CommonPath([Path, self.MetaFile.Dir]) != self.MetaFile.Dir):
2719 ErrMsg = "The include directory for the EDK II module in this line is invalid %s specified in %s FLAGS '%s'" % (Path, Tool, FlagOption)
2720 EdkLogger.error("build",
2721 PARAMETER_INVALID,
2722 ExtraData=ErrMsg,
2723 File=str(self.MetaFile))
2724
2725
2726 BuildOptionIncPathList += IncPathList
2727
2728 self._BuildOptionIncPathList = BuildOptionIncPathList
2729
2730 return self._BuildOptionIncPathList
2731
2732 ## Return a list of files which can be built from source
2733 #
2734 # What kind of files can be built is determined by build rules in
2735 # $(CONF_DIRECTORY)/build_rule.txt and toolchain family.
2736 #
2737 def _GetSourceFileList(self):
2738 if self._SourceFileList == None:
2739 self._SourceFileList = []
2740 for F in self.Module.Sources:
2741 # match tool chain
2742 if F.TagName not in ("", "*", self.ToolChain):
2743 EdkLogger.debug(EdkLogger.DEBUG_9, "The toolchain [%s] for processing file [%s] is found, "
2744 "but [%s] is needed" % (F.TagName, str(F), self.ToolChain))
2745 continue
2746 # match tool chain family
2747 if F.ToolChainFamily not in ("", "*", self.ToolChainFamily):
2748 EdkLogger.debug(
2749 EdkLogger.DEBUG_0,
2750 "The file [%s] must be built by tools of [%s], " \
2751 "but current toolchain family is [%s]" \
2752 % (str(F), F.ToolChainFamily, self.ToolChainFamily))
2753 continue
2754
2755 # add the file path into search path list for file including
2756 if F.Dir not in self.IncludePathList and self.AutoGenVersion >= 0x00010005:
2757 self.IncludePathList.insert(0, F.Dir)
2758 self._SourceFileList.append(F)
2759
2760 self._MatchBuildRuleOrder(self._SourceFileList)
2761
2762 for F in self._SourceFileList:
2763 self._ApplyBuildRule(F, TAB_UNKNOWN_FILE)
2764 return self._SourceFileList
2765
2766 def _MatchBuildRuleOrder(self, FileList):
2767 Order_Dict = {}
2768 self._GetModuleBuildOption()
2769 for SingleFile in FileList:
2770 if self.BuildRuleOrder and SingleFile.Ext in self.BuildRuleOrder and SingleFile.Ext in self.BuildRules:
2771 key = SingleFile.Path.split(SingleFile.Ext)[0]
2772 if key in Order_Dict:
2773 Order_Dict[key].append(SingleFile.Ext)
2774 else:
2775 Order_Dict[key] = [SingleFile.Ext]
2776
2777 RemoveList = []
2778 for F in Order_Dict:
2779 if len(Order_Dict[F]) > 1:
2780 Order_Dict[F].sort(key=lambda i: self.BuildRuleOrder.index(i))
2781 for Ext in Order_Dict[F][1:]:
2782 RemoveList.append(F + Ext)
2783
2784 for item in RemoveList:
2785 FileList.remove(item)
2786
2787 return FileList
2788
2789 ## Return the list of unicode files
2790 def _GetUnicodeFileList(self):
2791 if self._UnicodeFileList == None:
2792 if TAB_UNICODE_FILE in self.FileTypes:
2793 self._UnicodeFileList = self.FileTypes[TAB_UNICODE_FILE]
2794 else:
2795 self._UnicodeFileList = []
2796 return self._UnicodeFileList
2797
2798 ## Return a list of files which can be built from binary
2799 #
2800 # "Build" binary files are just to copy them to build directory.
2801 #
2802 # @retval list The list of files which can be built later
2803 #
2804 def _GetBinaryFiles(self):
2805 if self._BinaryFileList == None:
2806 self._BinaryFileList = []
2807 for F in self.Module.Binaries:
2808 if F.Target not in ['COMMON', '*'] and F.Target != self.BuildTarget:
2809 continue
2810 self._BinaryFileList.append(F)
2811 self._ApplyBuildRule(F, F.Type)
2812 return self._BinaryFileList
2813
2814 def _GetBuildRules(self):
2815 if self._BuildRules == None:
2816 BuildRules = {}
2817 BuildRuleDatabase = self.PlatformInfo.BuildRule
2818 for Type in BuildRuleDatabase.FileTypeList:
2819 #first try getting build rule by BuildRuleFamily
2820 RuleObject = BuildRuleDatabase[Type, self.BuildType, self.Arch, self.BuildRuleFamily]
2821 if not RuleObject:
2822 # build type is always module type, but ...
2823 if self.ModuleType != self.BuildType:
2824 RuleObject = BuildRuleDatabase[Type, self.ModuleType, self.Arch, self.BuildRuleFamily]
2825 #second try getting build rule by ToolChainFamily
2826 if not RuleObject:
2827 RuleObject = BuildRuleDatabase[Type, self.BuildType, self.Arch, self.ToolChainFamily]
2828 if not RuleObject:
2829 # build type is always module type, but ...
2830 if self.ModuleType != self.BuildType:
2831 RuleObject = BuildRuleDatabase[Type, self.ModuleType, self.Arch, self.ToolChainFamily]
2832 if not RuleObject:
2833 continue
2834 RuleObject = RuleObject.Instantiate(self.Macros)
2835 BuildRules[Type] = RuleObject
2836 for Ext in RuleObject.SourceFileExtList:
2837 BuildRules[Ext] = RuleObject
2838 self._BuildRules = BuildRules
2839 return self._BuildRules
2840
2841 def _ApplyBuildRule(self, File, FileType):
2842 if self._BuildTargets == None:
2843 self._IntroBuildTargetList = set()
2844 self._FinalBuildTargetList = set()
2845 self._BuildTargets = {}
2846 self._FileTypes = {}
2847
2848 SubDirectory = os.path.join(self.OutputDir, File.SubDir)
2849 if not os.path.exists(SubDirectory):
2850 CreateDirectory(SubDirectory)
2851 LastTarget = None
2852 RuleChain = []
2853 SourceList = [File]
2854 Index = 0
2855 #
2856 # Make sure to get build rule order value
2857 #
2858 self._GetModuleBuildOption()
2859
2860 while Index < len(SourceList):
2861 Source = SourceList[Index]
2862 Index = Index + 1
2863
2864 if Source != File:
2865 CreateDirectory(Source.Dir)
2866
2867 if File.IsBinary and File == Source and self._BinaryFileList != None and File in self._BinaryFileList:
2868 # Skip all files that are not binary libraries
2869 if not self.IsLibrary:
2870 continue
2871 RuleObject = self.BuildRules[TAB_DEFAULT_BINARY_FILE]
2872 elif FileType in self.BuildRules:
2873 RuleObject = self.BuildRules[FileType]
2874 elif Source.Ext in self.BuildRules:
2875 RuleObject = self.BuildRules[Source.Ext]
2876 else:
2877 # stop at no more rules
2878 if LastTarget:
2879 self._FinalBuildTargetList.add(LastTarget)
2880 break
2881
2882 FileType = RuleObject.SourceFileType
2883 if FileType not in self._FileTypes:
2884 self._FileTypes[FileType] = set()
2885 self._FileTypes[FileType].add(Source)
2886
2887 # stop at STATIC_LIBRARY for library
2888 if self.IsLibrary and FileType == TAB_STATIC_LIBRARY:
2889 if LastTarget:
2890 self._FinalBuildTargetList.add(LastTarget)
2891 break
2892
2893 Target = RuleObject.Apply(Source, self.BuildRuleOrder)
2894 if not Target:
2895 if LastTarget:
2896 self._FinalBuildTargetList.add(LastTarget)
2897 break
2898 elif not Target.Outputs:
2899 # Only do build for target with outputs
2900 self._FinalBuildTargetList.add(Target)
2901
2902 if FileType not in self._BuildTargets:
2903 self._BuildTargets[FileType] = set()
2904 self._BuildTargets[FileType].add(Target)
2905
2906 if not Source.IsBinary and Source == File:
2907 self._IntroBuildTargetList.add(Target)
2908
2909 # to avoid cyclic rule
2910 if FileType in RuleChain:
2911 break
2912
2913 RuleChain.append(FileType)
2914 SourceList.extend(Target.Outputs)
2915 LastTarget = Target
2916 FileType = TAB_UNKNOWN_FILE
2917
2918 def _GetTargets(self):
2919 if self._BuildTargets == None:
2920 self._IntroBuildTargetList = set()
2921 self._FinalBuildTargetList = set()
2922 self._BuildTargets = {}
2923 self._FileTypes = {}
2924
2925 #TRICK: call _GetSourceFileList to apply build rule for source files
2926 if self.SourceFileList:
2927 pass
2928
2929 #TRICK: call _GetBinaryFileList to apply build rule for binary files
2930 if self.BinaryFileList:
2931 pass
2932
2933 return self._BuildTargets
2934
2935 def _GetIntroTargetList(self):
2936 self._GetTargets()
2937 return self._IntroBuildTargetList
2938
2939 def _GetFinalTargetList(self):
2940 self._GetTargets()
2941 return self._FinalBuildTargetList
2942
2943 def _GetFileTypes(self):
2944 self._GetTargets()
2945 return self._FileTypes
2946
2947 ## Get the list of package object the module depends on
2948 #
2949 # @retval list The package object list
2950 #
2951 def _GetDependentPackageList(self):
2952 return self.Module.Packages
2953
2954 ## Return the list of auto-generated code file
2955 #
2956 # @retval list The list of auto-generated file
2957 #
2958 def _GetAutoGenFileList(self):
2959 UniStringAutoGenC = True
2960 UniStringBinBuffer = StringIO()
2961 if self.BuildType == 'UEFI_HII':
2962 UniStringAutoGenC = False
2963 if self._AutoGenFileList == None:
2964 self._AutoGenFileList = {}
2965 AutoGenC = TemplateString()
2966 AutoGenH = TemplateString()
2967 StringH = TemplateString()
2968 GenC.CreateCode(self, AutoGenC, AutoGenH, StringH, UniStringAutoGenC, UniStringBinBuffer)
2969 #
2970 # AutoGen.c is generated if there are library classes in inf, or there are object files
2971 #
2972 if str(AutoGenC) != "" and (len(self.Module.LibraryClasses) > 0
2973 or TAB_OBJECT_FILE in self.FileTypes):
2974 AutoFile = PathClass(gAutoGenCodeFileName, self.DebugDir)
2975 self._AutoGenFileList[AutoFile] = str(AutoGenC)
2976 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)
2977 if str(AutoGenH) != "":
2978 AutoFile = PathClass(gAutoGenHeaderFileName, self.DebugDir)
2979 self._AutoGenFileList[AutoFile] = str(AutoGenH)
2980 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)
2981 if str(StringH) != "":
2982 AutoFile = PathClass(gAutoGenStringFileName % {"module_name":self.Name}, self.DebugDir)
2983 self._AutoGenFileList[AutoFile] = str(StringH)
2984 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)
2985 if UniStringBinBuffer != None and UniStringBinBuffer.getvalue() != "":
2986 AutoFile = PathClass(gAutoGenStringFormFileName % {"module_name":self.Name}, self.OutputDir)
2987 self._AutoGenFileList[AutoFile] = UniStringBinBuffer.getvalue()
2988 AutoFile.IsBinary = True
2989 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)
2990 if UniStringBinBuffer != None:
2991 UniStringBinBuffer.close()
2992 return self._AutoGenFileList
2993
2994 ## Return the list of library modules explicitly or implicityly used by this module
2995 def _GetLibraryList(self):
2996 if self._DependentLibraryList == None:
2997 # only merge library classes and PCD for non-library module
2998 if self.IsLibrary:
2999 self._DependentLibraryList = []
3000 else:
3001 if self.AutoGenVersion < 0x00010005:
3002 self._DependentLibraryList = self.PlatformInfo.ResolveLibraryReference(self.Module)
3003 else:
3004 self._DependentLibraryList = self.PlatformInfo.ApplyLibraryInstance(self.Module)
3005 return self._DependentLibraryList
3006
3007 @staticmethod
3008 def UpdateComments(Recver, Src):
3009 for Key in Src:
3010 if Key not in Recver:
3011 Recver[Key] = []
3012 Recver[Key].extend(Src[Key])
3013 ## Get the list of PCDs from current module
3014 #
3015 # @retval list The list of PCD
3016 #
3017 def _GetModulePcdList(self):
3018 if self._ModulePcdList == None:
3019 # apply PCD settings from platform
3020 self._ModulePcdList = self.PlatformInfo.ApplyPcdSetting(self.Module, self.Module.Pcds)
3021 self.UpdateComments(self._PcdComments, self.Module.PcdComments)
3022 return self._ModulePcdList
3023
3024 ## Get the list of PCDs from dependent libraries
3025 #
3026 # @retval list The list of PCD
3027 #
3028 def _GetLibraryPcdList(self):
3029 if self._LibraryPcdList == None:
3030 Pcds = sdict()
3031 if not self.IsLibrary:
3032 # get PCDs from dependent libraries
3033 for Library in self.DependentLibraryList:
3034 self.UpdateComments(self._PcdComments, Library.PcdComments)
3035 for Key in Library.Pcds:
3036 # skip duplicated PCDs
3037 if Key in self.Module.Pcds or Key in Pcds:
3038 continue
3039 Pcds[Key] = copy.copy(Library.Pcds[Key])
3040 # apply PCD settings from platform
3041 self._LibraryPcdList = self.PlatformInfo.ApplyPcdSetting(self.Module, Pcds)
3042 else:
3043 self._LibraryPcdList = []
3044 return self._LibraryPcdList
3045
3046 ## Get the GUID value mapping
3047 #
3048 # @retval dict The mapping between GUID cname and its value
3049 #
3050 def _GetGuidList(self):
3051 if self._GuidList == None:
3052 self._GuidList = sdict()
3053 self._GuidList.update(self.Module.Guids)
3054 for Library in self.DependentLibraryList:
3055 self._GuidList.update(Library.Guids)
3056 self.UpdateComments(self._GuidComments, Library.GuidComments)
3057 self.UpdateComments(self._GuidComments, self.Module.GuidComments)
3058 return self._GuidList
3059
3060 def GetGuidsUsedByPcd(self):
3061 if self._GuidsUsedByPcd == None:
3062 self._GuidsUsedByPcd = sdict()
3063 self._GuidsUsedByPcd.update(self.Module.GetGuidsUsedByPcd())
3064 for Library in self.DependentLibraryList:
3065 self._GuidsUsedByPcd.update(Library.GetGuidsUsedByPcd())
3066 return self._GuidsUsedByPcd
3067 ## Get the protocol value mapping
3068 #
3069 # @retval dict The mapping between protocol cname and its value
3070 #
3071 def _GetProtocolList(self):
3072 if self._ProtocolList == None:
3073 self._ProtocolList = sdict()
3074 self._ProtocolList.update(self.Module.Protocols)
3075 for Library in self.DependentLibraryList:
3076 self._ProtocolList.update(Library.Protocols)
3077 self.UpdateComments(self._ProtocolComments, Library.ProtocolComments)
3078 self.UpdateComments(self._ProtocolComments, self.Module.ProtocolComments)
3079 return self._ProtocolList
3080
3081 ## Get the PPI value mapping
3082 #
3083 # @retval dict The mapping between PPI cname and its value
3084 #
3085 def _GetPpiList(self):
3086 if self._PpiList == None:
3087 self._PpiList = sdict()
3088 self._PpiList.update(self.Module.Ppis)
3089 for Library in self.DependentLibraryList:
3090 self._PpiList.update(Library.Ppis)
3091 self.UpdateComments(self._PpiComments, Library.PpiComments)
3092 self.UpdateComments(self._PpiComments, self.Module.PpiComments)
3093 return self._PpiList
3094
3095 ## Get the list of include search path
3096 #
3097 # @retval list The list path
3098 #
3099 def _GetIncludePathList(self):
3100 if self._IncludePathList == None:
3101 self._IncludePathList = []
3102 if self.AutoGenVersion < 0x00010005:
3103 for Inc in self.Module.Includes:
3104 if Inc not in self._IncludePathList:
3105 self._IncludePathList.append(Inc)
3106 # for Edk modules
3107 Inc = path.join(Inc, self.Arch.capitalize())
3108 if os.path.exists(Inc) and Inc not in self._IncludePathList:
3109 self._IncludePathList.append(Inc)
3110 # Edk module needs to put DEBUG_DIR at the end of search path and not to use SOURCE_DIR all the time
3111 self._IncludePathList.append(self.DebugDir)
3112 else:
3113 self._IncludePathList.append(self.MetaFile.Dir)
3114 self._IncludePathList.append(self.DebugDir)
3115
3116 for Package in self.Module.Packages:
3117 PackageDir = mws.join(self.WorkspaceDir, Package.MetaFile.Dir)
3118 if PackageDir not in self._IncludePathList:
3119 self._IncludePathList.append(PackageDir)
3120 for Inc in Package.Includes:
3121 if Inc not in self._IncludePathList:
3122 self._IncludePathList.append(str(Inc))
3123 return self._IncludePathList
3124
3125 ## Get HII EX PCDs which maybe used by VFR
3126 #
3127 # efivarstore used by VFR may relate with HII EX PCDs
3128 # Get the variable name and GUID from efivarstore and HII EX PCD
3129 # List the HII EX PCDs in As Built INF if both name and GUID match.
3130 #
3131 # @retval list HII EX PCDs
3132 #
3133 def _GetPcdsMaybeUsedByVfr(self):
3134 if not self.SourceFileList:
3135 return []
3136
3137 NameGuids = []
3138 for SrcFile in self.SourceFileList:
3139 if SrcFile.Ext.lower() != '.vfr':
3140 continue
3141 Vfri = os.path.join(self.OutputDir, SrcFile.BaseName + '.i')
3142 if not os.path.exists(Vfri):
3143 continue
3144 VfriFile = open(Vfri, 'r')
3145 Content = VfriFile.read()
3146 VfriFile.close()
3147 Pos = Content.find('efivarstore')
3148 while Pos != -1:
3149 #
3150 # Make sure 'efivarstore' is the start of efivarstore statement
3151 # In case of the value of 'name' (name = efivarstore) is equal to 'efivarstore'
3152 #
3153 Index = Pos - 1
3154 while Index >= 0 and Content[Index] in ' \t\r\n':
3155 Index -= 1
3156 if Index >= 0 and Content[Index] != ';':
3157 Pos = Content.find('efivarstore', Pos + len('efivarstore'))
3158 continue
3159 #
3160 # 'efivarstore' must be followed by name and guid
3161 #
3162 Name = gEfiVarStoreNamePattern.search(Content, Pos)
3163 if not Name:
3164 break
3165 Guid = gEfiVarStoreGuidPattern.search(Content, Pos)
3166 if not Guid:
3167 break
3168 NameArray = ConvertStringToByteArray('L"' + Name.group(1) + '"')
3169 NameGuids.append((NameArray, GuidStructureStringToGuidString(Guid.group(1))))
3170 Pos = Content.find('efivarstore', Name.end())
3171 if not NameGuids:
3172 return []
3173 HiiExPcds = []
3174 for Pcd in self.PlatformInfo.Platform.Pcds.values():
3175 if Pcd.Type != TAB_PCDS_DYNAMIC_EX_HII:
3176 continue
3177 for SkuName in Pcd.SkuInfoList:
3178 SkuInfo = Pcd.SkuInfoList[SkuName]
3179 Name = ConvertStringToByteArray(SkuInfo.VariableName)
3180 Value = GuidValue(SkuInfo.VariableGuid, self.PlatformInfo.PackageList)
3181 if not Value:
3182 continue
3183 Guid = GuidStructureStringToGuidString(Value)
3184 if (Name, Guid) in NameGuids and Pcd not in HiiExPcds:
3185 HiiExPcds.append(Pcd)
3186 break
3187
3188 return HiiExPcds
3189
3190 def _GenOffsetBin(self):
3191 VfrUniBaseName = {}
3192 for SourceFile in self.Module.Sources:
3193 if SourceFile.Type.upper() == ".VFR" :
3194 #
3195 # search the .map file to find the offset of vfr binary in the PE32+/TE file.
3196 #
3197 VfrUniBaseName[SourceFile.BaseName] = (SourceFile.BaseName + "Bin")
3198 if SourceFile.Type.upper() == ".UNI" :
3199 #
3200 # search the .map file to find the offset of Uni strings binary in the PE32+/TE file.
3201 #
3202 VfrUniBaseName["UniOffsetName"] = (self.Name + "Strings")
3203
3204 if len(VfrUniBaseName) == 0:
3205 return None
3206 MapFileName = os.path.join(self.OutputDir, self.Name + ".map")
3207 EfiFileName = os.path.join(self.OutputDir, self.Name + ".efi")
3208 VfrUniOffsetList = GetVariableOffset(MapFileName, EfiFileName, VfrUniBaseName.values())
3209 if not VfrUniOffsetList:
3210 return None
3211
3212 OutputName = '%sOffset.bin' % self.Name
3213 UniVfrOffsetFileName = os.path.join( self.OutputDir, OutputName)
3214
3215 try:
3216 fInputfile = open(UniVfrOffsetFileName, "wb+", 0)
3217 except:
3218 EdkLogger.error("build", FILE_OPEN_FAILURE, "File open failed for %s" % UniVfrOffsetFileName,None)
3219
3220 # Use a instance of StringIO to cache data
3221 fStringIO = StringIO('')
3222
3223 for Item in VfrUniOffsetList:
3224 if (Item[0].find("Strings") != -1):
3225 #
3226 # UNI offset in image.
3227 # GUID + Offset
3228 # { 0x8913c5e0, 0x33f6, 0x4d86, { 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66 } }
3229 #
3230 UniGuid = [0xe0, 0xc5, 0x13, 0x89, 0xf6, 0x33, 0x86, 0x4d, 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66]
3231 UniGuid = [chr(ItemGuid) for ItemGuid in UniGuid]
3232 fStringIO.write(''.join(UniGuid))
3233 UniValue = pack ('Q', int (Item[1], 16))
3234 fStringIO.write (UniValue)
3235 else:
3236 #
3237 # VFR binary offset in image.
3238 # GUID + Offset
3239 # { 0xd0bc7cb4, 0x6a47, 0x495f, { 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2 } };
3240 #
3241 VfrGuid = [0xb4, 0x7c, 0xbc, 0xd0, 0x47, 0x6a, 0x5f, 0x49, 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2]
3242 VfrGuid = [chr(ItemGuid) for ItemGuid in VfrGuid]
3243 fStringIO.write(''.join(VfrGuid))
3244 type (Item[1])
3245 VfrValue = pack ('Q', int (Item[1], 16))
3246 fStringIO.write (VfrValue)
3247 #
3248 # write data into file.
3249 #
3250 try :
3251 fInputfile.write (fStringIO.getvalue())
3252 except:
3253 EdkLogger.error("build", FILE_WRITE_FAILURE, "Write data to file %s failed, please check whether the "
3254 "file been locked or using by other applications." %UniVfrOffsetFileName,None)
3255
3256 fStringIO.close ()
3257 fInputfile.close ()
3258 return OutputName
3259
3260 ## Create AsBuilt INF file the module
3261 #
3262 def CreateAsBuiltInf(self):
3263 if self.IsAsBuiltInfCreated:
3264 return
3265
3266 # Skip the following code for EDK I inf
3267 if self.AutoGenVersion < 0x00010005:
3268 return
3269
3270 # Skip the following code for libraries
3271 if self.IsLibrary:
3272 return
3273
3274 # Skip the following code for modules with no source files
3275 if self.SourceFileList == None or self.SourceFileList == []:
3276 return
3277
3278 # Skip the following code for modules without any binary files
3279 if self.BinaryFileList <> None and self.BinaryFileList <> []:
3280 return
3281
3282 ### TODO: How to handles mixed source and binary modules
3283
3284 # Find all DynamicEx and PatchableInModule PCDs used by this module and dependent libraries
3285 # Also find all packages that the DynamicEx PCDs depend on
3286 Pcds = []
3287 PatchablePcds = {}
3288 Packages = []
3289 PcdCheckList = []
3290 PcdTokenSpaceList = []
3291 for Pcd in self.ModulePcdList + self.LibraryPcdList:
3292 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
3293 PatchablePcds[Pcd.TokenCName] = Pcd
3294 PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, 'PatchableInModule'))
3295 elif Pcd.Type in GenC.gDynamicExPcd:
3296 if Pcd not in Pcds:
3297 Pcds += [Pcd]
3298 PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, 'DynamicEx'))
3299 PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, 'Dynamic'))
3300 PcdTokenSpaceList.append(Pcd.TokenSpaceGuidCName)
3301 GuidList = sdict()
3302 GuidList.update(self.GuidList)
3303 for TokenSpace in self.GetGuidsUsedByPcd():
3304 # If token space is not referred by patch PCD or Ex PCD, remove the GUID from GUID list
3305 # The GUIDs in GUIDs section should really be the GUIDs in source INF or referred by Ex an patch PCDs
3306 if TokenSpace not in PcdTokenSpaceList and TokenSpace in GuidList:
3307 GuidList.pop(TokenSpace)
3308 CheckList = (GuidList, self.PpiList, self.ProtocolList, PcdCheckList)
3309 for Package in self.DerivedPackageList:
3310 if Package in Packages:
3311 continue
3312 BeChecked = (Package.Guids, Package.Ppis, Package.Protocols, Package.Pcds)
3313 Found = False
3314 for Index in range(len(BeChecked)):
3315 for Item in CheckList[Index]:
3316 if Item in BeChecked[Index]:
3317 Packages += [Package]
3318 Found = True
3319 break
3320 if Found: break
3321
3322 VfrPcds = self._GetPcdsMaybeUsedByVfr()
3323 for Pkg in self.PlatformInfo.PackageList:
3324 if Pkg in Packages:
3325 continue
3326 for VfrPcd in VfrPcds:
3327 if ((VfrPcd.TokenCName, VfrPcd.TokenSpaceGuidCName, 'DynamicEx') in Pkg.Pcds or
3328 (VfrPcd.TokenCName, VfrPcd.TokenSpaceGuidCName, 'Dynamic') in Pkg.Pcds):
3329 Packages += [Pkg]
3330 break
3331
3332 ModuleType = self.ModuleType
3333 if ModuleType == 'UEFI_DRIVER' and self.DepexGenerated:
3334 ModuleType = 'DXE_DRIVER'
3335
3336 DriverType = ''
3337 if self.PcdIsDriver != '':
3338 DriverType = self.PcdIsDriver
3339
3340 Guid = self.Guid
3341 MDefs = self.Module.Defines
3342
3343 AsBuiltInfDict = {
3344 'module_name' : self.Name,
3345 'module_guid' : Guid,
3346 'module_module_type' : ModuleType,
3347 'module_version_string' : [MDefs['VERSION_STRING']] if 'VERSION_STRING' in MDefs else [],
3348 'pcd_is_driver_string' : [],
3349 'module_uefi_specification_version' : [],
3350 'module_pi_specification_version' : [],
3351 'module_entry_point' : self.Module.ModuleEntryPointList,
3352 'module_unload_image' : self.Module.ModuleUnloadImageList,
3353 'module_constructor' : self.Module.ConstructorList,
3354 'module_destructor' : self.Module.DestructorList,
3355 'module_shadow' : [MDefs['SHADOW']] if 'SHADOW' in MDefs else [],
3356 'module_pci_vendor_id' : [MDefs['PCI_VENDOR_ID']] if 'PCI_VENDOR_ID' in MDefs else [],
3357 'module_pci_device_id' : [MDefs['PCI_DEVICE_ID']] if 'PCI_DEVICE_ID' in MDefs else [],
3358 'module_pci_class_code' : [MDefs['PCI_CLASS_CODE']] if 'PCI_CLASS_CODE' in MDefs else [],
3359 'module_pci_revision' : [MDefs['PCI_REVISION']] if 'PCI_REVISION' in MDefs else [],
3360 'module_build_number' : [MDefs['BUILD_NUMBER']] if 'BUILD_NUMBER' in MDefs else [],
3361 'module_spec' : [MDefs['SPEC']] if 'SPEC' in MDefs else [],
3362 'module_uefi_hii_resource_section' : [MDefs['UEFI_HII_RESOURCE_SECTION']] if 'UEFI_HII_RESOURCE_SECTION' in MDefs else [],
3363 'module_uni_file' : [MDefs['MODULE_UNI_FILE']] if 'MODULE_UNI_FILE' in MDefs else [],
3364 'module_arch' : self.Arch,
3365 'package_item' : ['%s' % (Package.MetaFile.File.replace('\\', '/')) for Package in Packages],
3366 'binary_item' : [],
3367 'patchablepcd_item' : [],
3368 'pcd_item' : [],
3369 'protocol_item' : [],
3370 'ppi_item' : [],
3371 'guid_item' : [],
3372 'flags_item' : [],
3373 'libraryclasses_item' : []
3374 }
3375
3376 if self.AutoGenVersion > int(gInfSpecVersion, 0):
3377 AsBuiltInfDict['module_inf_version'] = '0x%08x' % self.AutoGenVersion
3378 else:
3379 AsBuiltInfDict['module_inf_version'] = gInfSpecVersion
3380
3381 if DriverType:
3382 AsBuiltInfDict['pcd_is_driver_string'] += [DriverType]
3383
3384 if 'UEFI_SPECIFICATION_VERSION' in self.Specification:
3385 AsBuiltInfDict['module_uefi_specification_version'] += [self.Specification['UEFI_SPECIFICATION_VERSION']]
3386 if 'PI_SPECIFICATION_VERSION' in self.Specification:
3387 AsBuiltInfDict['module_pi_specification_version'] += [self.Specification['PI_SPECIFICATION_VERSION']]
3388
3389 OutputDir = self.OutputDir.replace('\\', '/').strip('/')
3390 if self.ModuleType in ['BASE', 'USER_DEFINED']:
3391 for Item in self.CodaTargetList:
3392 File = Item.Target.Path.replace('\\', '/').strip('/').replace(OutputDir, '').strip('/')
3393 if Item.Target.Ext.lower() == '.aml':
3394 AsBuiltInfDict['binary_item'] += ['ASL|' + File]
3395 elif Item.Target.Ext.lower() == '.acpi':
3396 AsBuiltInfDict['binary_item'] += ['ACPI|' + File]
3397 else:
3398 AsBuiltInfDict['binary_item'] += ['BIN|' + File]
3399 else:
3400 for Item in self.CodaTargetList:
3401 File = Item.Target.Path.replace('\\', '/').strip('/').replace(OutputDir, '').strip('/')
3402 if Item.Target.Ext.lower() == '.efi':
3403 AsBuiltInfDict['binary_item'] += ['PE32|' + self.Name + '.efi']
3404 else:
3405 AsBuiltInfDict['binary_item'] += ['BIN|' + File]
3406 if self.DepexGenerated:
3407 if self.ModuleType in ['PEIM']:
3408 AsBuiltInfDict['binary_item'] += ['PEI_DEPEX|' + self.Name + '.depex']
3409 if self.ModuleType in ['DXE_DRIVER', 'DXE_RUNTIME_DRIVER', 'DXE_SAL_DRIVER', 'UEFI_DRIVER']:
3410 AsBuiltInfDict['binary_item'] += ['DXE_DEPEX|' + self.Name + '.depex']
3411 if self.ModuleType in ['DXE_SMM_DRIVER']:
3412 AsBuiltInfDict['binary_item'] += ['SMM_DEPEX|' + self.Name + '.depex']
3413
3414 Bin = self._GenOffsetBin()
3415 if Bin:
3416 AsBuiltInfDict['binary_item'] += ['BIN|%s' % Bin]
3417
3418 for Root, Dirs, Files in os.walk(OutputDir):
3419 for File in Files:
3420 if File.lower().endswith('.pdb'):
3421 AsBuiltInfDict['binary_item'] += ['DISPOSABLE|' + File]
3422 HeaderComments = self.Module.HeaderComments
3423 StartPos = 0
3424 for Index in range(len(HeaderComments)):
3425 if HeaderComments[Index].find('@BinaryHeader') != -1:
3426 HeaderComments[Index] = HeaderComments[Index].replace('@BinaryHeader', '@file')
3427 StartPos = Index
3428 break
3429 AsBuiltInfDict['header_comments'] = '\n'.join(HeaderComments[StartPos:]).replace(':#', '://')
3430 AsBuiltInfDict['tail_comments'] = '\n'.join(self.Module.TailComments)
3431
3432 GenList = [
3433 (self.ProtocolList, self._ProtocolComments, 'protocol_item'),
3434 (self.PpiList, self._PpiComments, 'ppi_item'),
3435 (GuidList, self._GuidComments, 'guid_item')
3436 ]
3437 for Item in GenList:
3438 for CName in Item[0]:
3439 Comments = ''
3440 if CName in Item[1]:
3441 Comments = '\n '.join(Item[1][CName])
3442 Entry = CName
3443 if Comments:
3444 Entry = Comments + '\n ' + CName
3445 AsBuiltInfDict[Item[2]].append(Entry)
3446 PatchList = parsePcdInfoFromMapFile(
3447 os.path.join(self.OutputDir, self.Name + '.map'),
3448 os.path.join(self.OutputDir, self.Name + '.efi')
3449 )
3450 if PatchList:
3451 for PatchPcd in PatchList:
3452 if PatchPcd[0] not in PatchablePcds:
3453 continue
3454 Pcd = PatchablePcds[PatchPcd[0]]
3455 PcdValue = ''
3456 if Pcd.DatumType != 'VOID*':
3457 HexFormat = '0x%02x'
3458 if Pcd.DatumType == 'UINT16':
3459 HexFormat = '0x%04x'
3460 elif Pcd.DatumType == 'UINT32':
3461 HexFormat = '0x%08x'
3462 elif Pcd.DatumType == 'UINT64':
3463 HexFormat = '0x%016x'
3464 PcdValue = HexFormat % int(Pcd.DefaultValue, 0)
3465 else:
3466 if Pcd.MaxDatumSize == None or Pcd.MaxDatumSize == '':
3467 EdkLogger.error("build", AUTOGEN_ERROR,
3468 "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName)
3469 )
3470 ArraySize = int(Pcd.MaxDatumSize, 0)
3471 PcdValue = Pcd.DefaultValue
3472 if PcdValue[0] != '{':
3473 Unicode = False
3474 if PcdValue[0] == 'L':
3475 Unicode = True
3476 PcdValue = PcdValue.lstrip('L')
3477 PcdValue = eval(PcdValue)
3478 NewValue = '{'
3479 for Index in range(0, len(PcdValue)):
3480 if Unicode:
3481 CharVal = ord(PcdValue[Index])
3482 NewValue = NewValue + '0x%02x' % (CharVal & 0x00FF) + ', ' \
3483 + '0x%02x' % (CharVal >> 8) + ', '
3484 else:
3485 NewValue = NewValue + '0x%02x' % (ord(PcdValue[Index]) % 0x100) + ', '
3486 Padding = '0x00, '
3487 if Unicode:
3488 Padding = Padding * 2
3489 ArraySize = ArraySize / 2
3490 if ArraySize < (len(PcdValue) + 1):
3491 EdkLogger.error("build", AUTOGEN_ERROR,
3492 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName)
3493 )
3494 if ArraySize > len(PcdValue) + 1:
3495 NewValue = NewValue + Padding * (ArraySize - len(PcdValue) - 1)
3496 PcdValue = NewValue + Padding.strip().rstrip(',') + '}'
3497 elif len(PcdValue.split(',')) <= ArraySize:
3498 PcdValue = PcdValue.rstrip('}') + ', 0x00' * (ArraySize - len(PcdValue.split(',')))
3499 PcdValue += '}'
3500 else:
3501 EdkLogger.error("build", AUTOGEN_ERROR,
3502 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName)
3503 )
3504 PcdItem = '%s.%s|%s|0x%X' % \
3505 (Pcd.TokenSpaceGuidCName, Pcd.TokenCName, PcdValue, PatchPcd[1])
3506 PcdComments = ''
3507 if (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in self._PcdComments:
3508 PcdComments = '\n '.join(self._PcdComments[Pcd.TokenSpaceGuidCName, Pcd.TokenCName])
3509 if PcdComments:
3510 PcdItem = PcdComments + '\n ' + PcdItem
3511 AsBuiltInfDict['patchablepcd_item'].append(PcdItem)
3512
3513 HiiPcds = []
3514 for Pcd in Pcds + VfrPcds:
3515 PcdComments = ''
3516 PcdCommentList = []
3517 HiiInfo = ''
3518 SkuId = ''
3519 if Pcd.Type == TAB_PCDS_DYNAMIC_EX_HII:
3520 for SkuName in Pcd.SkuInfoList:
3521 SkuInfo = Pcd.SkuInfoList[SkuName]
3522 SkuId = SkuInfo.SkuId
3523 HiiInfo = '## %s|%s|%s' % (SkuInfo.VariableName, SkuInfo.VariableGuid, SkuInfo.VariableOffset)
3524 break
3525 if SkuId:
3526 #
3527 # Don't generate duplicated HII PCD
3528 #
3529 if (SkuId, Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in HiiPcds:
3530 continue
3531 else:
3532 HiiPcds.append((SkuId, Pcd.TokenSpaceGuidCName, Pcd.TokenCName))
3533 if (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in self._PcdComments:
3534 PcdCommentList = self._PcdComments[Pcd.TokenSpaceGuidCName, Pcd.TokenCName][:]
3535 if HiiInfo:
3536 UsageIndex = -1
3537 UsageStr = ''
3538 for Index, Comment in enumerate(PcdCommentList):
3539 for Usage in UsageList:
3540 if Comment.find(Usage) != -1:
3541 UsageStr = Usage
3542 UsageIndex = Index
3543 break
3544 if UsageIndex != -1:
3545 PcdCommentList[UsageIndex] = '## %s %s %s' % (UsageStr, HiiInfo, PcdCommentList[UsageIndex].replace(UsageStr, ''))
3546 else:
3547 PcdCommentList.append('## UNDEFINED ' + HiiInfo)
3548 PcdComments = '\n '.join(PcdCommentList)
3549 PcdEntry = Pcd.TokenSpaceGuidCName + '.' + Pcd.TokenCName
3550 if PcdComments:
3551 PcdEntry = PcdComments + '\n ' + PcdEntry
3552 AsBuiltInfDict['pcd_item'] += [PcdEntry]
3553 for Item in self.BuildOption:
3554 if 'FLAGS' in self.BuildOption[Item]:
3555 AsBuiltInfDict['flags_item'] += ['%s:%s_%s_%s_%s_FLAGS = %s' % (self.ToolChainFamily, self.BuildTarget, self.ToolChain, self.Arch, Item, self.BuildOption[Item]['FLAGS'].strip())]
3556
3557 # Generated LibraryClasses section in comments.
3558 for Library in self.LibraryAutoGenList:
3559 AsBuiltInfDict['libraryclasses_item'] += [Library.MetaFile.File.replace('\\', '/')]
3560
3561 # Generated depex expression section in comments.
3562 AsBuiltInfDict['depexsection_item'] = ''
3563 DepexExpresion = self._GetDepexExpresionString()
3564 if DepexExpresion:
3565 AsBuiltInfDict['depexsection_item'] = DepexExpresion
3566
3567 AsBuiltInf = TemplateString()
3568 AsBuiltInf.Append(gAsBuiltInfHeaderString.Replace(AsBuiltInfDict))
3569
3570 SaveFileOnChange(os.path.join(self.OutputDir, self.Name + '.inf'), str(AsBuiltInf), False)
3571
3572 self.IsAsBuiltInfCreated = True
3573
3574 ## Create makefile for the module and its dependent libraries
3575 #
3576 # @param CreateLibraryMakeFile Flag indicating if or not the makefiles of
3577 # dependent libraries will be created
3578 #
3579 def CreateMakeFile(self, CreateLibraryMakeFile=True):
3580 # Ignore generating makefile when it is a binary module
3581 if self.IsBinaryModule:
3582 return
3583
3584 if self.IsMakeFileCreated:
3585 return
3586
3587 if not self.IsLibrary and CreateLibraryMakeFile:
3588 for LibraryAutoGen in self.LibraryAutoGenList:
3589 LibraryAutoGen.CreateMakeFile()
3590
3591 if len(self.CustomMakefile) == 0:
3592 Makefile = GenMake.ModuleMakefile(self)
3593 else:
3594 Makefile = GenMake.CustomMakefile(self)
3595 if Makefile.Generate():
3596 EdkLogger.debug(EdkLogger.DEBUG_9, "Generated makefile for module %s [%s]" %
3597 (self.Name, self.Arch))
3598 else:
3599 EdkLogger.debug(EdkLogger.DEBUG_9, "Skipped the generation of makefile for module %s [%s]" %
3600 (self.Name, self.Arch))
3601
3602 self.IsMakeFileCreated = True
3603
3604 def CopyBinaryFiles(self):
3605 for File in self.Module.Binaries:
3606 SrcPath = File.Path
3607 DstPath = os.path.join(self.OutputDir , os.path.basename(SrcPath))
3608 CopyLongFilePath(SrcPath, DstPath)
3609 ## Create autogen code for the module and its dependent libraries
3610 #
3611 # @param CreateLibraryCodeFile Flag indicating if or not the code of
3612 # dependent libraries will be created
3613 #
3614 def CreateCodeFile(self, CreateLibraryCodeFile=True):
3615 if self.IsCodeFileCreated:
3616 return
3617
3618 # Need to generate PcdDatabase even PcdDriver is binarymodule
3619 if self.IsBinaryModule and self.PcdIsDriver != '':
3620 CreatePcdDatabaseCode(self, TemplateString(), TemplateString())
3621 return
3622 if self.IsBinaryModule:
3623 if self.IsLibrary:
3624 self.CopyBinaryFiles()
3625 return
3626
3627 if not self.IsLibrary and CreateLibraryCodeFile:
3628 for LibraryAutoGen in self.LibraryAutoGenList:
3629 LibraryAutoGen.CreateCodeFile()
3630
3631 AutoGenList = []
3632 IgoredAutoGenList = []
3633
3634 for File in self.AutoGenFileList:
3635 if GenC.Generate(File.Path, self.AutoGenFileList[File], File.IsBinary):
3636 #Ignore Edk AutoGen.c
3637 if self.AutoGenVersion < 0x00010005 and File.Name == 'AutoGen.c':
3638 continue
3639
3640 AutoGenList.append(str(File))
3641 else:
3642 IgoredAutoGenList.append(str(File))
3643
3644 # Skip the following code for EDK I inf
3645 if self.AutoGenVersion < 0x00010005:
3646 return
3647
3648 for ModuleType in self.DepexList:
3649 # Ignore empty [depex] section or [depex] section for "USER_DEFINED" module
3650 if len(self.DepexList[ModuleType]) == 0 or ModuleType == "USER_DEFINED":
3651 continue
3652
3653 Dpx = GenDepex.DependencyExpression(self.DepexList[ModuleType], ModuleType, True)
3654 DpxFile = gAutoGenDepexFileName % {"module_name" : self.Name}
3655
3656 if len(Dpx.PostfixNotation) <> 0:
3657 self.DepexGenerated = True
3658
3659 if Dpx.Generate(path.join(self.OutputDir, DpxFile)):
3660 AutoGenList.append(str(DpxFile))
3661 else:
3662 IgoredAutoGenList.append(str(DpxFile))
3663
3664 if IgoredAutoGenList == []:
3665 EdkLogger.debug(EdkLogger.DEBUG_9, "Generated [%s] files for module %s [%s]" %
3666 (" ".join(AutoGenList), self.Name, self.Arch))
3667 elif AutoGenList == []:
3668 EdkLogger.debug(EdkLogger.DEBUG_9, "Skipped the generation of [%s] files for module %s [%s]" %
3669 (" ".join(IgoredAutoGenList), self.Name, self.Arch))
3670 else:
3671 EdkLogger.debug(EdkLogger.DEBUG_9, "Generated [%s] (skipped %s) files for module %s [%s]" %
3672 (" ".join(AutoGenList), " ".join(IgoredAutoGenList), self.Name, self.Arch))
3673
3674 self.IsCodeFileCreated = True
3675 return AutoGenList
3676
3677 ## Summarize the ModuleAutoGen objects of all libraries used by this module
3678 def _GetLibraryAutoGenList(self):
3679 if self._LibraryAutoGenList == None:
3680 self._LibraryAutoGenList = []
3681 for Library in self.DependentLibraryList:
3682 La = ModuleAutoGen(
3683 self.Workspace,
3684 Library.MetaFile,
3685 self.BuildTarget,
3686 self.ToolChain,
3687 self.Arch,
3688 self.PlatformInfo.MetaFile
3689 )
3690 if La not in self._LibraryAutoGenList:
3691 self._LibraryAutoGenList.append(La)
3692 for Lib in La.CodaTargetList:
3693 self._ApplyBuildRule(Lib.Target, TAB_UNKNOWN_FILE)
3694 return self._LibraryAutoGenList
3695
3696 Module = property(_GetModule)
3697 Name = property(_GetBaseName)
3698 Guid = property(_GetGuid)
3699 Version = property(_GetVersion)
3700 ModuleType = property(_GetModuleType)
3701 ComponentType = property(_GetComponentType)
3702 BuildType = property(_GetBuildType)
3703 PcdIsDriver = property(_GetPcdIsDriver)
3704 AutoGenVersion = property(_GetAutoGenVersion)
3705 Macros = property(_GetMacros)
3706 Specification = property(_GetSpecification)
3707
3708 IsLibrary = property(_IsLibrary)
3709 IsBinaryModule = property(_IsBinaryModule)
3710 BuildDir = property(_GetBuildDir)
3711 OutputDir = property(_GetOutputDir)
3712 DebugDir = property(_GetDebugDir)
3713 MakeFileDir = property(_GetMakeFileDir)
3714 CustomMakefile = property(_GetCustomMakefile)
3715
3716 IncludePathList = property(_GetIncludePathList)
3717 AutoGenFileList = property(_GetAutoGenFileList)
3718 UnicodeFileList = property(_GetUnicodeFileList)
3719 SourceFileList = property(_GetSourceFileList)
3720 BinaryFileList = property(_GetBinaryFiles) # FileType : [File List]
3721 Targets = property(_GetTargets)
3722 IntroTargetList = property(_GetIntroTargetList)
3723 CodaTargetList = property(_GetFinalTargetList)
3724 FileTypes = property(_GetFileTypes)
3725 BuildRules = property(_GetBuildRules)
3726
3727 DependentPackageList = property(_GetDependentPackageList)
3728 DependentLibraryList = property(_GetLibraryList)
3729 LibraryAutoGenList = property(_GetLibraryAutoGenList)
3730 DerivedPackageList = property(_GetDerivedPackageList)
3731
3732 ModulePcdList = property(_GetModulePcdList)
3733 LibraryPcdList = property(_GetLibraryPcdList)
3734 GuidList = property(_GetGuidList)
3735 ProtocolList = property(_GetProtocolList)
3736 PpiList = property(_GetPpiList)
3737 DepexList = property(_GetDepexTokenList)
3738 DxsFile = property(_GetDxsFile)
3739 DepexExpressionList = property(_GetDepexExpressionTokenList)
3740 BuildOption = property(_GetModuleBuildOption)
3741 BuildOptionIncPathList = property(_GetBuildOptionIncPathList)
3742 BuildCommand = property(_GetBuildCommand)
3743
3744 FixedAtBuildPcds = property(_GetFixedAtBuildPcds)
3745
3746 # This acts like the main() function for the script, unless it is 'import'ed into another script.
3747 if __name__ == '__main__':
3748 pass
3749