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