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