]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/AutoGen/ModuleAutoGen.py
MdePkg/Include: Add DCC and BCM2835 SPCR UART types
[mirror_edk2.git] / BaseTools / Source / Python / AutoGen / ModuleAutoGen.py
CommitLineData
e8449e1d
FB
1## @file\r
2# Create makefile for MS nmake and GNU make\r
3#\r
4# Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>\r
5# SPDX-License-Identifier: BSD-2-Clause-Patent\r
6#\r
7from __future__ import absolute_import\r
8from AutoGen.AutoGen import AutoGen\r
fc8b8dea 9from Common.LongFilePathSupport import LongFilePath, CopyLongFilePath\r
e8449e1d
FB
10from Common.BuildToolError import *\r
11from Common.DataType import *\r
12from Common.Misc import *\r
13from Common.StringUtils import NormPath,GetSplitList\r
14from collections import defaultdict\r
15from Workspace.WorkspaceCommon import OrderedListDict\r
16import os.path as path\r
17import copy\r
18import hashlib\r
19from . import InfSectionParser\r
20from . import GenC\r
21from . import GenMake\r
22from . import GenDepex\r
23from io import BytesIO\r
24from GenPatchPcdTable.GenPatchPcdTable import parsePcdInfoFromMapFile\r
25from Workspace.MetaFileCommentParser import UsageList\r
26from .GenPcdDb import CreatePcdDatabaseCode\r
27from Common.caching import cached_class_function\r
28from AutoGen.ModuleAutoGenHelper import PlatformInfo,WorkSpaceInfo\r
0e7e7a26 29import json\r
94459080 30import tempfile\r
e8449e1d
FB
31\r
32## Mapping Makefile type\r
33gMakeTypeMap = {TAB_COMPILER_MSFT:"nmake", "GCC":"gmake"}\r
34#\r
35# Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT\r
36# is the former use /I , the Latter used -I to specify include directories\r
37#\r
38gBuildOptIncludePatternMsft = re.compile(r"(?:.*?)/I[ \t]*([^ ]*)", re.MULTILINE | re.DOTALL)\r
39gBuildOptIncludePatternOther = re.compile(r"(?:.*?)-I[ \t]*([^ ]*)", re.MULTILINE | re.DOTALL)\r
40\r
41## default file name for AutoGen\r
42gAutoGenCodeFileName = "AutoGen.c"\r
43gAutoGenHeaderFileName = "AutoGen.h"\r
44gAutoGenStringFileName = "%(module_name)sStrDefs.h"\r
45gAutoGenStringFormFileName = "%(module_name)sStrDefs.hpk"\r
46gAutoGenDepexFileName = "%(module_name)s.depex"\r
47gAutoGenImageDefFileName = "%(module_name)sImgDefs.h"\r
48gAutoGenIdfFileName = "%(module_name)sIdf.hpk"\r
49gInfSpecVersion = "0x00010017"\r
50\r
51#\r
52# Match name = variable\r
53#\r
54gEfiVarStoreNamePattern = re.compile("\s*name\s*=\s*(\w+)")\r
55#\r
56# The format of guid in efivarstore statement likes following and must be correct:\r
57# guid = {0xA04A27f4, 0xDF00, 0x4D42, {0xB5, 0x52, 0x39, 0x51, 0x13, 0x02, 0x11, 0x3D}}\r
58#\r
59gEfiVarStoreGuidPattern = re.compile("\s*guid\s*=\s*({.*?{.*?}\s*})")\r
60\r
61#\r
62# Template string to generic AsBuilt INF\r
63#\r
64gAsBuiltInfHeaderString = TemplateString("""${header_comments}\r
65\r
66# DO NOT EDIT\r
67# FILE auto-generated\r
68\r
69[Defines]\r
70 INF_VERSION = ${module_inf_version}\r
71 BASE_NAME = ${module_name}\r
72 FILE_GUID = ${module_guid}\r
73 MODULE_TYPE = ${module_module_type}${BEGIN}\r
74 VERSION_STRING = ${module_version_string}${END}${BEGIN}\r
75 PCD_IS_DRIVER = ${pcd_is_driver_string}${END}${BEGIN}\r
76 UEFI_SPECIFICATION_VERSION = ${module_uefi_specification_version}${END}${BEGIN}\r
77 PI_SPECIFICATION_VERSION = ${module_pi_specification_version}${END}${BEGIN}\r
78 ENTRY_POINT = ${module_entry_point}${END}${BEGIN}\r
79 UNLOAD_IMAGE = ${module_unload_image}${END}${BEGIN}\r
80 CONSTRUCTOR = ${module_constructor}${END}${BEGIN}\r
81 DESTRUCTOR = ${module_destructor}${END}${BEGIN}\r
82 SHADOW = ${module_shadow}${END}${BEGIN}\r
83 PCI_VENDOR_ID = ${module_pci_vendor_id}${END}${BEGIN}\r
84 PCI_DEVICE_ID = ${module_pci_device_id}${END}${BEGIN}\r
85 PCI_CLASS_CODE = ${module_pci_class_code}${END}${BEGIN}\r
86 PCI_REVISION = ${module_pci_revision}${END}${BEGIN}\r
87 BUILD_NUMBER = ${module_build_number}${END}${BEGIN}\r
88 SPEC = ${module_spec}${END}${BEGIN}\r
89 UEFI_HII_RESOURCE_SECTION = ${module_uefi_hii_resource_section}${END}${BEGIN}\r
90 MODULE_UNI_FILE = ${module_uni_file}${END}\r
91\r
92[Packages.${module_arch}]${BEGIN}\r
93 ${package_item}${END}\r
94\r
95[Binaries.${module_arch}]${BEGIN}\r
96 ${binary_item}${END}\r
97\r
98[PatchPcd.${module_arch}]${BEGIN}\r
99 ${patchablepcd_item}\r
100${END}\r
101\r
102[Protocols.${module_arch}]${BEGIN}\r
103 ${protocol_item}\r
104${END}\r
105\r
106[Ppis.${module_arch}]${BEGIN}\r
107 ${ppi_item}\r
108${END}\r
109\r
110[Guids.${module_arch}]${BEGIN}\r
111 ${guid_item}\r
112${END}\r
113\r
114[PcdEx.${module_arch}]${BEGIN}\r
115 ${pcd_item}\r
116${END}\r
117\r
118[LibraryClasses.${module_arch}]\r
119## @LIB_INSTANCES${BEGIN}\r
120# ${libraryclasses_item}${END}\r
121\r
122${depexsection_item}\r
123\r
124${userextension_tianocore_item}\r
125\r
126${tail_comments}\r
127\r
128[BuildOptions.${module_arch}]\r
129## @AsBuilt${BEGIN}\r
130## ${flags_item}${END}\r
131""")\r
132#\r
133# extend lists contained in a dictionary with lists stored in another dictionary\r
134# if CopyToDict is not derived from DefaultDict(list) then this may raise exception\r
135#\r
136def ExtendCopyDictionaryLists(CopyToDict, CopyFromDict):\r
137 for Key in CopyFromDict:\r
138 CopyToDict[Key].extend(CopyFromDict[Key])\r
139\r
140# Create a directory specified by a set of path elements and return the full path\r
141def _MakeDir(PathList):\r
142 RetVal = path.join(*PathList)\r
143 CreateDirectory(RetVal)\r
144 return RetVal\r
145\r
146#\r
147# Convert string to C format array\r
148#\r
149def _ConvertStringToByteArray(Value):\r
150 Value = Value.strip()\r
151 if not Value:\r
152 return None\r
153 if Value[0] == '{':\r
154 if not Value.endswith('}'):\r
155 return None\r
156 Value = Value.replace(' ', '').replace('{', '').replace('}', '')\r
157 ValFields = Value.split(',')\r
158 try:\r
159 for Index in range(len(ValFields)):\r
160 ValFields[Index] = str(int(ValFields[Index], 0))\r
161 except ValueError:\r
162 return None\r
163 Value = '{' + ','.join(ValFields) + '}'\r
164 return Value\r
165\r
166 Unicode = False\r
167 if Value.startswith('L"'):\r
168 if not Value.endswith('"'):\r
169 return None\r
170 Value = Value[1:]\r
171 Unicode = True\r
172 elif not Value.startswith('"') or not Value.endswith('"'):\r
173 return None\r
174\r
175 Value = eval(Value) # translate escape character\r
176 NewValue = '{'\r
177 for Index in range(0, len(Value)):\r
178 if Unicode:\r
179 NewValue = NewValue + str(ord(Value[Index]) % 0x10000) + ','\r
180 else:\r
181 NewValue = NewValue + str(ord(Value[Index]) % 0x100) + ','\r
182 Value = NewValue + '0}'\r
183 return Value\r
184\r
185## ModuleAutoGen class\r
186#\r
187# This class encapsules the AutoGen behaviors for the build tools. In addition to\r
188# the generation of AutoGen.h and AutoGen.c, it will generate *.depex file according\r
189# to the [depex] section in module's inf file.\r
190#\r
191class ModuleAutoGen(AutoGen):\r
192 # call super().__init__ then call the worker function with different parameter count\r
193 def __init__(self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):\r
194 if not hasattr(self, "_Init"):\r
195 self._InitWorker(Workspace, MetaFile, Target, Toolchain, Arch, *args)\r
196 self._Init = True\r
197\r
198 ## Cache the timestamps of metafiles of every module in a class attribute\r
199 #\r
200 TimeDict = {}\r
201\r
202 def __new__(cls, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):\r
203# check if this module is employed by active platform\r
204 if not PlatformInfo(Workspace, args[0], Target, Toolchain, Arch,args[-1]).ValidModule(MetaFile):\r
205 EdkLogger.verbose("Module [%s] for [%s] is not employed by active platform\n" \\r
206 % (MetaFile, Arch))\r
207 return None\r
208 return super(ModuleAutoGen, cls).__new__(cls, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)\r
209\r
210 ## Initialize ModuleAutoGen\r
211 #\r
212 # @param Workspace EdkIIWorkspaceBuild object\r
213 # @param ModuleFile The path of module file\r
214 # @param Target Build target (DEBUG, RELEASE)\r
215 # @param Toolchain Name of tool chain\r
216 # @param Arch The arch the module supports\r
217 # @param PlatformFile Platform meta-file\r
218 #\r
219 def _InitWorker(self, Workspace, ModuleFile, Target, Toolchain, Arch, PlatformFile,DataPipe):\r
220 EdkLogger.debug(EdkLogger.DEBUG_9, "AutoGen module [%s] [%s]" % (ModuleFile, Arch))\r
221 GlobalData.gProcessingFile = "%s [%s, %s, %s]" % (ModuleFile, Arch, Toolchain, Target)\r
222\r
a000d5d1 223 self.Workspace = Workspace\r
e8449e1d
FB
224 self.WorkspaceDir = ""\r
225 self.PlatformInfo = None\r
226 self.DataPipe = DataPipe\r
227 self.__init_platform_info__()\r
228 self.MetaFile = ModuleFile\r
229 self.SourceDir = self.MetaFile.SubDir\r
230 self.SourceDir = mws.relpath(self.SourceDir, self.WorkspaceDir)\r
231\r
232 self.ToolChain = Toolchain\r
233 self.BuildTarget = Target\r
234 self.Arch = Arch\r
235 self.ToolChainFamily = self.PlatformInfo.ToolChainFamily\r
236 self.BuildRuleFamily = self.PlatformInfo.BuildRuleFamily\r
237\r
238 self.IsCodeFileCreated = False\r
239 self.IsAsBuiltInfCreated = False\r
240 self.DepexGenerated = False\r
241\r
242 self.BuildDatabase = self.Workspace.BuildDatabase\r
243 self.BuildRuleOrder = None\r
244 self.BuildTime = 0\r
245\r
246 self._GuidComments = OrderedListDict()\r
247 self._ProtocolComments = OrderedListDict()\r
248 self._PpiComments = OrderedListDict()\r
249 self._BuildTargets = None\r
250 self._IntroBuildTargetList = None\r
251 self._FinalBuildTargetList = None\r
252 self._FileTypes = None\r
253\r
254 self.AutoGenDepSet = set()\r
255 self.ReferenceModules = []\r
256 self.ConstPcd = {}\r
0e7e7a26
SS
257 self.Makefile = None\r
258 self.FileDependCache = {}\r
e8449e1d
FB
259\r
260 def __init_platform_info__(self):\r
261 pinfo = self.DataPipe.Get("P_Info")\r
e8449e1d
FB
262 self.WorkspaceDir = pinfo.get("WorkspaceDir")\r
263 self.PlatformInfo = PlatformInfo(self.Workspace,pinfo.get("ActivePlatform"),pinfo.get("Target"),pinfo.get("ToolChain"),pinfo.get("Arch"),self.DataPipe)\r
264 ## hash() operator of ModuleAutoGen\r
265 #\r
266 # The module file path and arch string will be used to represent\r
267 # hash value of this object\r
268 #\r
269 # @retval int Hash value of the module file path and arch\r
270 #\r
271 @cached_class_function\r
272 def __hash__(self):\r
273 return hash((self.MetaFile, self.Arch))\r
274 def __repr__(self):\r
275 return "%s [%s]" % (self.MetaFile, self.Arch)\r
276\r
277 # Get FixedAtBuild Pcds of this Module\r
278 @cached_property\r
279 def FixedAtBuildPcds(self):\r
280 RetVal = []\r
281 for Pcd in self.ModulePcdList:\r
282 if Pcd.Type != TAB_PCDS_FIXED_AT_BUILD:\r
283 continue\r
284 if Pcd not in RetVal:\r
285 RetVal.append(Pcd)\r
286 return RetVal\r
287\r
288 @cached_property\r
289 def FixedVoidTypePcds(self):\r
290 RetVal = {}\r
291 for Pcd in self.FixedAtBuildPcds:\r
292 if Pcd.DatumType == TAB_VOID:\r
293 if '.'.join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName)) not in RetVal:\r
294 RetVal['.'.join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName))] = Pcd.DefaultValue\r
295 return RetVal\r
296\r
297 @property\r
298 def UniqueBaseName(self):\r
299 ModuleNames = self.DataPipe.Get("M_Name")\r
300 if not ModuleNames:\r
301 return self.Name\r
76e12fa3 302 return ModuleNames.get((self.Name,self.MetaFile),self.Name)\r
e8449e1d
FB
303\r
304 # Macros could be used in build_rule.txt (also Makefile)\r
305 @cached_property\r
306 def Macros(self):\r
307 return OrderedDict((\r
308 ("WORKSPACE" ,self.WorkspaceDir),\r
309 ("MODULE_NAME" ,self.Name),\r
310 ("MODULE_NAME_GUID" ,self.UniqueBaseName),\r
311 ("MODULE_GUID" ,self.Guid),\r
312 ("MODULE_VERSION" ,self.Version),\r
313 ("MODULE_TYPE" ,self.ModuleType),\r
314 ("MODULE_FILE" ,str(self.MetaFile)),\r
315 ("MODULE_FILE_BASE_NAME" ,self.MetaFile.BaseName),\r
316 ("MODULE_RELATIVE_DIR" ,self.SourceDir),\r
317 ("MODULE_DIR" ,self.SourceDir),\r
318 ("BASE_NAME" ,self.Name),\r
319 ("ARCH" ,self.Arch),\r
320 ("TOOLCHAIN" ,self.ToolChain),\r
321 ("TOOLCHAIN_TAG" ,self.ToolChain),\r
322 ("TOOL_CHAIN_TAG" ,self.ToolChain),\r
323 ("TARGET" ,self.BuildTarget),\r
324 ("BUILD_DIR" ,self.PlatformInfo.BuildDir),\r
325 ("BIN_DIR" ,os.path.join(self.PlatformInfo.BuildDir, self.Arch)),\r
326 ("LIB_DIR" ,os.path.join(self.PlatformInfo.BuildDir, self.Arch)),\r
327 ("MODULE_BUILD_DIR" ,self.BuildDir),\r
328 ("OUTPUT_DIR" ,self.OutputDir),\r
329 ("DEBUG_DIR" ,self.DebugDir),\r
330 ("DEST_DIR_OUTPUT" ,self.OutputDir),\r
331 ("DEST_DIR_DEBUG" ,self.DebugDir),\r
332 ("PLATFORM_NAME" ,self.PlatformInfo.Name),\r
333 ("PLATFORM_GUID" ,self.PlatformInfo.Guid),\r
334 ("PLATFORM_VERSION" ,self.PlatformInfo.Version),\r
335 ("PLATFORM_RELATIVE_DIR" ,self.PlatformInfo.SourceDir),\r
336 ("PLATFORM_DIR" ,mws.join(self.WorkspaceDir, self.PlatformInfo.SourceDir)),\r
337 ("PLATFORM_OUTPUT_DIR" ,self.PlatformInfo.OutputDir),\r
338 ("FFS_OUTPUT_DIR" ,self.FfsOutputDir)\r
339 ))\r
340\r
341 ## Return the module build data object\r
342 @cached_property\r
343 def Module(self):\r
344 return self.BuildDatabase[self.MetaFile, self.Arch, self.BuildTarget, self.ToolChain]\r
345\r
346 ## Return the module name\r
347 @cached_property\r
348 def Name(self):\r
349 return self.Module.BaseName\r
350\r
351 ## Return the module DxsFile if exist\r
352 @cached_property\r
353 def DxsFile(self):\r
354 return self.Module.DxsFile\r
355\r
356 ## Return the module meta-file GUID\r
357 @cached_property\r
358 def Guid(self):\r
359 #\r
360 # To build same module more than once, the module path with FILE_GUID overridden has\r
361 # the file name FILE_GUIDmodule.inf, but the relative path (self.MetaFile.File) is the real path\r
362 # in DSC. The overridden GUID can be retrieved from file name\r
363 #\r
364 if os.path.basename(self.MetaFile.File) != os.path.basename(self.MetaFile.Path):\r
365 #\r
366 # Length of GUID is 36\r
367 #\r
368 return os.path.basename(self.MetaFile.Path)[:36]\r
369 return self.Module.Guid\r
370\r
371 ## Return the module version\r
372 @cached_property\r
373 def Version(self):\r
374 return self.Module.Version\r
375\r
376 ## Return the module type\r
377 @cached_property\r
378 def ModuleType(self):\r
379 return self.Module.ModuleType\r
380\r
381 ## Return the component type (for Edk.x style of module)\r
382 @cached_property\r
383 def ComponentType(self):\r
384 return self.Module.ComponentType\r
385\r
386 ## Return the build type\r
387 @cached_property\r
388 def BuildType(self):\r
389 return self.Module.BuildType\r
390\r
391 ## Return the PCD_IS_DRIVER setting\r
392 @cached_property\r
393 def PcdIsDriver(self):\r
394 return self.Module.PcdIsDriver\r
395\r
396 ## Return the autogen version, i.e. module meta-file version\r
397 @cached_property\r
398 def AutoGenVersion(self):\r
399 return self.Module.AutoGenVersion\r
400\r
401 ## Check if the module is library or not\r
402 @cached_property\r
403 def IsLibrary(self):\r
404 return bool(self.Module.LibraryClass)\r
405\r
406 ## Check if the module is binary module or not\r
407 @cached_property\r
408 def IsBinaryModule(self):\r
409 return self.Module.IsBinaryModule\r
410\r
411 ## Return the directory to store intermediate files of the module\r
412 @cached_property\r
413 def BuildDir(self):\r
414 return _MakeDir((\r
415 self.PlatformInfo.BuildDir,\r
416 self.Arch,\r
417 self.SourceDir,\r
418 self.MetaFile.BaseName\r
419 ))\r
420\r
421 ## Return the directory to store the intermediate object files of the module\r
422 @cached_property\r
423 def OutputDir(self):\r
424 return _MakeDir((self.BuildDir, "OUTPUT"))\r
425\r
426 ## Return the directory path to store ffs file\r
427 @cached_property\r
428 def FfsOutputDir(self):\r
429 if GlobalData.gFdfParser:\r
430 return path.join(self.PlatformInfo.BuildDir, TAB_FV_DIRECTORY, "Ffs", self.Guid + self.Name)\r
431 return ''\r
432\r
433 ## Return the directory to store auto-gened source files of the module\r
434 @cached_property\r
435 def DebugDir(self):\r
436 return _MakeDir((self.BuildDir, "DEBUG"))\r
437\r
438 ## Return the path of custom file\r
439 @cached_property\r
440 def CustomMakefile(self):\r
441 RetVal = {}\r
442 for Type in self.Module.CustomMakefile:\r
443 MakeType = gMakeTypeMap[Type] if Type in gMakeTypeMap else 'nmake'\r
444 File = os.path.join(self.SourceDir, self.Module.CustomMakefile[Type])\r
445 RetVal[MakeType] = File\r
446 return RetVal\r
447\r
448 ## Return the directory of the makefile\r
449 #\r
450 # @retval string The directory string of module's makefile\r
451 #\r
452 @cached_property\r
453 def MakeFileDir(self):\r
454 return self.BuildDir\r
455\r
456 ## Return build command string\r
457 #\r
458 # @retval string Build command string\r
459 #\r
460 @cached_property\r
461 def BuildCommand(self):\r
462 return self.PlatformInfo.BuildCommand\r
463\r
bf1ea933
FZ
464 ## Get Module package and Platform package\r
465 #\r
466 # @retval list The list of package object\r
467 #\r
468 @cached_property\r
469 def PackageList(self):\r
470 PkagList = []\r
471 if self.Module.Packages:\r
472 PkagList.extend(self.Module.Packages)\r
473 Platform = self.BuildDatabase[self.PlatformInfo.MetaFile, self.Arch, self.BuildTarget, self.ToolChain]\r
474 for Package in Platform.Packages:\r
475 if Package in PkagList:\r
476 continue\r
477 PkagList.append(Package)\r
478 return PkagList\r
479\r
480 ## Get object list of all packages the module and its dependent libraries belong to and the Platform depends on\r
e8449e1d
FB
481 #\r
482 # @retval list The list of package object\r
483 #\r
484 @cached_property\r
485 def DerivedPackageList(self):\r
486 PackageList = []\r
bf1ea933
FZ
487 PackageList.extend(self.PackageList)\r
488 for M in self.DependentLibraryList:\r
e8449e1d
FB
489 for Package in M.Packages:\r
490 if Package in PackageList:\r
491 continue\r
492 PackageList.append(Package)\r
493 return PackageList\r
494\r
495 ## Get the depex string\r
496 #\r
497 # @return : a string contain all depex expression.\r
498 def _GetDepexExpresionString(self):\r
499 DepexStr = ''\r
500 DepexList = []\r
501 ## DPX_SOURCE IN Define section.\r
502 if self.Module.DxsFile:\r
503 return DepexStr\r
504 for M in [self.Module] + self.DependentLibraryList:\r
505 Filename = M.MetaFile.Path\r
506 InfObj = InfSectionParser.InfSectionParser(Filename)\r
507 DepexExpressionList = InfObj.GetDepexExpresionList()\r
508 for DepexExpression in DepexExpressionList:\r
509 for key in DepexExpression:\r
510 Arch, ModuleType = key\r
511 DepexExpr = [x for x in DepexExpression[key] if not str(x).startswith('#')]\r
512 # the type of build module is USER_DEFINED.\r
513 # All different DEPEX section tags would be copied into the As Built INF file\r
514 # and there would be separate DEPEX section tags\r
515 if self.ModuleType.upper() == SUP_MODULE_USER_DEFINED or self.ModuleType.upper() == SUP_MODULE_HOST_APPLICATION:\r
516 if (Arch.upper() == self.Arch.upper()) and (ModuleType.upper() != TAB_ARCH_COMMON):\r
517 DepexList.append({(Arch, ModuleType): DepexExpr})\r
518 else:\r
519 if Arch.upper() == TAB_ARCH_COMMON or \\r
520 (Arch.upper() == self.Arch.upper() and \\r
521 ModuleType.upper() in [TAB_ARCH_COMMON, self.ModuleType.upper()]):\r
522 DepexList.append({(Arch, ModuleType): DepexExpr})\r
523\r
524 #the type of build module is USER_DEFINED.\r
525 if self.ModuleType.upper() == SUP_MODULE_USER_DEFINED or self.ModuleType.upper() == SUP_MODULE_HOST_APPLICATION:\r
526 for Depex in DepexList:\r
527 for key in Depex:\r
528 DepexStr += '[Depex.%s.%s]\n' % key\r
529 DepexStr += '\n'.join('# '+ val for val in Depex[key])\r
530 DepexStr += '\n\n'\r
531 if not DepexStr:\r
532 return '[Depex.%s]\n' % self.Arch\r
533 return DepexStr\r
534\r
535 #the type of build module not is USER_DEFINED.\r
536 Count = 0\r
537 for Depex in DepexList:\r
538 Count += 1\r
539 if DepexStr != '':\r
540 DepexStr += ' AND '\r
541 DepexStr += '('\r
542 for D in Depex.values():\r
543 DepexStr += ' '.join(val for val in D)\r
544 Index = DepexStr.find('END')\r
545 if Index > -1 and Index == len(DepexStr) - 3:\r
546 DepexStr = DepexStr[:-3]\r
547 DepexStr = DepexStr.strip()\r
548 DepexStr += ')'\r
549 if Count == 1:\r
550 DepexStr = DepexStr.lstrip('(').rstrip(')').strip()\r
551 if not DepexStr:\r
552 return '[Depex.%s]\n' % self.Arch\r
553 return '[Depex.%s]\n# ' % self.Arch + DepexStr\r
554\r
555 ## Merge dependency expression\r
556 #\r
557 # @retval list The token list of the dependency expression after parsed\r
558 #\r
559 @cached_property\r
560 def DepexList(self):\r
561 if self.DxsFile or self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:\r
562 return {}\r
563\r
564 DepexList = []\r
565 #\r
566 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expression\r
567 #\r
568 FixedVoidTypePcds = {}\r
569 for M in [self] + self.LibraryAutoGenList:\r
570 FixedVoidTypePcds.update(M.FixedVoidTypePcds)\r
571 for M in [self] + self.LibraryAutoGenList:\r
572 Inherited = False\r
573 for D in M.Module.Depex[self.Arch, self.ModuleType]:\r
574 if DepexList != []:\r
575 DepexList.append('AND')\r
576 DepexList.append('(')\r
577 #replace D with value if D is FixedAtBuild PCD\r
578 NewList = []\r
579 for item in D:\r
580 if '.' not in item:\r
581 NewList.append(item)\r
582 else:\r
583 try:\r
584 Value = FixedVoidTypePcds[item]\r
585 if len(Value.split(',')) != 16:\r
586 EdkLogger.error("build", FORMAT_INVALID,\r
587 "{} used in [Depex] section should be used as FixedAtBuild type and VOID* datum type and 16 bytes in the module.".format(item))\r
588 NewList.append(Value)\r
589 except:\r
590 EdkLogger.error("build", FORMAT_INVALID, "{} used in [Depex] section should be used as FixedAtBuild type and VOID* datum type in the module.".format(item))\r
591\r
592 DepexList.extend(NewList)\r
593 if DepexList[-1] == 'END': # no need of a END at this time\r
594 DepexList.pop()\r
595 DepexList.append(')')\r
596 Inherited = True\r
597 if Inherited:\r
598 EdkLogger.verbose("DEPEX[%s] (+%s) = %s" % (self.Name, M.Module.BaseName, DepexList))\r
599 if 'BEFORE' in DepexList or 'AFTER' in DepexList:\r
600 break\r
601 if len(DepexList) > 0:\r
602 EdkLogger.verbose('')\r
603 return {self.ModuleType:DepexList}\r
604\r
605 ## Merge dependency expression\r
606 #\r
607 # @retval list The token list of the dependency expression after parsed\r
608 #\r
609 @cached_property\r
610 def DepexExpressionDict(self):\r
611 if self.DxsFile or self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:\r
612 return {}\r
613\r
614 DepexExpressionString = ''\r
615 #\r
616 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion\r
617 #\r
618 for M in [self.Module] + self.DependentLibraryList:\r
619 Inherited = False\r
620 for D in M.DepexExpression[self.Arch, self.ModuleType]:\r
621 if DepexExpressionString != '':\r
622 DepexExpressionString += ' AND '\r
623 DepexExpressionString += '('\r
624 DepexExpressionString += D\r
625 DepexExpressionString = DepexExpressionString.rstrip('END').strip()\r
626 DepexExpressionString += ')'\r
627 Inherited = True\r
628 if Inherited:\r
629 EdkLogger.verbose("DEPEX[%s] (+%s) = %s" % (self.Name, M.BaseName, DepexExpressionString))\r
630 if 'BEFORE' in DepexExpressionString or 'AFTER' in DepexExpressionString:\r
631 break\r
632 if len(DepexExpressionString) > 0:\r
633 EdkLogger.verbose('')\r
634\r
635 return {self.ModuleType:DepexExpressionString}\r
636\r
637 # Get the tiano core user extension, it is contain dependent library.\r
638 # @retval: a list contain tiano core userextension.\r
639 #\r
640 def _GetTianoCoreUserExtensionList(self):\r
641 TianoCoreUserExtentionList = []\r
642 for M in [self.Module] + self.DependentLibraryList:\r
643 Filename = M.MetaFile.Path\r
644 InfObj = InfSectionParser.InfSectionParser(Filename)\r
645 TianoCoreUserExtenList = InfObj.GetUserExtensionTianoCore()\r
646 for TianoCoreUserExtent in TianoCoreUserExtenList:\r
647 for Section in TianoCoreUserExtent:\r
648 ItemList = Section.split(TAB_SPLIT)\r
649 Arch = self.Arch\r
650 if len(ItemList) == 4:\r
651 Arch = ItemList[3]\r
652 if Arch.upper() == TAB_ARCH_COMMON or Arch.upper() == self.Arch.upper():\r
653 TianoCoreList = []\r
654 TianoCoreList.extend([TAB_SECTION_START + Section + TAB_SECTION_END])\r
655 TianoCoreList.extend(TianoCoreUserExtent[Section][:])\r
656 TianoCoreList.append('\n')\r
657 TianoCoreUserExtentionList.append(TianoCoreList)\r
658\r
659 return TianoCoreUserExtentionList\r
660\r
661 ## Return the list of specification version required for the module\r
662 #\r
663 # @retval list The list of specification defined in module file\r
664 #\r
665 @cached_property\r
666 def Specification(self):\r
667 return self.Module.Specification\r
668\r
669 ## Tool option for the module build\r
670 #\r
671 # @param PlatformInfo The object of PlatformBuildInfo\r
672 # @retval dict The dict containing valid options\r
673 #\r
674 @cached_property\r
675 def BuildOption(self):\r
676 RetVal, self.BuildRuleOrder = self.PlatformInfo.ApplyBuildOption(self.Module)\r
677 if self.BuildRuleOrder:\r
678 self.BuildRuleOrder = ['.%s' % Ext for Ext in self.BuildRuleOrder.split()]\r
679 return RetVal\r
680\r
681 ## Get include path list from tool option for the module build\r
682 #\r
683 # @retval list The include path list\r
684 #\r
685 @cached_property\r
686 def BuildOptionIncPathList(self):\r
687 #\r
688 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT\r
689 # is the former use /I , the Latter used -I to specify include directories\r
690 #\r
691 if self.PlatformInfo.ToolChainFamily in (TAB_COMPILER_MSFT):\r
692 BuildOptIncludeRegEx = gBuildOptIncludePatternMsft\r
693 elif self.PlatformInfo.ToolChainFamily in ('INTEL', 'GCC', 'RVCT'):\r
694 BuildOptIncludeRegEx = gBuildOptIncludePatternOther\r
695 else:\r
696 #\r
697 # New ToolChainFamily, don't known whether there is option to specify include directories\r
698 #\r
699 return []\r
700\r
701 RetVal = []\r
702 for Tool in ('CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'ASM'):\r
703 try:\r
704 FlagOption = self.BuildOption[Tool]['FLAGS']\r
705 except KeyError:\r
706 FlagOption = ''\r
707\r
708 if self.ToolChainFamily != 'RVCT':\r
709 IncPathList = [NormPath(Path, self.Macros) for Path in BuildOptIncludeRegEx.findall(FlagOption)]\r
710 else:\r
711 #\r
712 # RVCT may specify a list of directory seperated by commas\r
713 #\r
714 IncPathList = []\r
715 for Path in BuildOptIncludeRegEx.findall(FlagOption):\r
716 PathList = GetSplitList(Path, TAB_COMMA_SPLIT)\r
717 IncPathList.extend(NormPath(PathEntry, self.Macros) for PathEntry in PathList)\r
718\r
719 #\r
720 # EDK II modules must not reference header files outside of the packages they depend on or\r
721 # within the module's directory tree. Report error if violation.\r
722 #\r
723 if GlobalData.gDisableIncludePathCheck == False:\r
724 for Path in IncPathList:\r
725 if (Path not in self.IncludePathList) and (CommonPath([Path, self.MetaFile.Dir]) != self.MetaFile.Dir):\r
726 ErrMsg = "The include directory for the EDK II module in this line is invalid %s specified in %s FLAGS '%s'" % (Path, Tool, FlagOption)\r
727 EdkLogger.error("build",\r
728 PARAMETER_INVALID,\r
729 ExtraData=ErrMsg,\r
730 File=str(self.MetaFile))\r
731 RetVal += IncPathList\r
732 return RetVal\r
733\r
734 ## Return a list of files which can be built from source\r
735 #\r
736 # What kind of files can be built is determined by build rules in\r
737 # $(CONF_DIRECTORY)/build_rule.txt and toolchain family.\r
738 #\r
739 @cached_property\r
740 def SourceFileList(self):\r
741 RetVal = []\r
742 ToolChainTagSet = {"", TAB_STAR, self.ToolChain}\r
743 ToolChainFamilySet = {"", TAB_STAR, self.ToolChainFamily, self.BuildRuleFamily}\r
744 for F in self.Module.Sources:\r
745 # match tool chain\r
746 if F.TagName not in ToolChainTagSet:\r
747 EdkLogger.debug(EdkLogger.DEBUG_9, "The toolchain [%s] for processing file [%s] is found, "\r
748 "but [%s] is currently used" % (F.TagName, str(F), self.ToolChain))\r
749 continue\r
750 # match tool chain family or build rule family\r
751 if F.ToolChainFamily not in ToolChainFamilySet:\r
752 EdkLogger.debug(\r
753 EdkLogger.DEBUG_0,\r
754 "The file [%s] must be built by tools of [%s], " \\r
755 "but current toolchain family is [%s], buildrule family is [%s]" \\r
756 % (str(F), F.ToolChainFamily, self.ToolChainFamily, self.BuildRuleFamily))\r
757 continue\r
758\r
759 # add the file path into search path list for file including\r
760 if F.Dir not in self.IncludePathList:\r
761 self.IncludePathList.insert(0, F.Dir)\r
762 RetVal.append(F)\r
763\r
764 self._MatchBuildRuleOrder(RetVal)\r
765\r
766 for F in RetVal:\r
767 self._ApplyBuildRule(F, TAB_UNKNOWN_FILE)\r
768 return RetVal\r
769\r
770 def _MatchBuildRuleOrder(self, FileList):\r
771 Order_Dict = {}\r
772 self.BuildOption\r
773 for SingleFile in FileList:\r
774 if self.BuildRuleOrder and SingleFile.Ext in self.BuildRuleOrder and SingleFile.Ext in self.BuildRules:\r
775 key = SingleFile.Path.rsplit(SingleFile.Ext,1)[0]\r
776 if key in Order_Dict:\r
777 Order_Dict[key].append(SingleFile.Ext)\r
778 else:\r
779 Order_Dict[key] = [SingleFile.Ext]\r
780\r
781 RemoveList = []\r
782 for F in Order_Dict:\r
783 if len(Order_Dict[F]) > 1:\r
784 Order_Dict[F].sort(key=lambda i: self.BuildRuleOrder.index(i))\r
785 for Ext in Order_Dict[F][1:]:\r
786 RemoveList.append(F + Ext)\r
787\r
788 for item in RemoveList:\r
789 FileList.remove(item)\r
790\r
791 return FileList\r
792\r
793 ## Return the list of unicode files\r
794 @cached_property\r
795 def UnicodeFileList(self):\r
796 return self.FileTypes.get(TAB_UNICODE_FILE,[])\r
797\r
798 ## Return the list of vfr files\r
799 @cached_property\r
800 def VfrFileList(self):\r
801 return self.FileTypes.get(TAB_VFR_FILE, [])\r
802\r
803 ## Return the list of Image Definition files\r
804 @cached_property\r
805 def IdfFileList(self):\r
806 return self.FileTypes.get(TAB_IMAGE_FILE,[])\r
807\r
808 ## Return a list of files which can be built from binary\r
809 #\r
810 # "Build" binary files are just to copy them to build directory.\r
811 #\r
812 # @retval list The list of files which can be built later\r
813 #\r
814 @cached_property\r
815 def BinaryFileList(self):\r
816 RetVal = []\r
817 for F in self.Module.Binaries:\r
818 if F.Target not in [TAB_ARCH_COMMON, TAB_STAR] and F.Target != self.BuildTarget:\r
819 continue\r
820 RetVal.append(F)\r
821 self._ApplyBuildRule(F, F.Type, BinaryFileList=RetVal)\r
822 return RetVal\r
823\r
824 @cached_property\r
825 def BuildRules(self):\r
826 RetVal = {}\r
827 BuildRuleDatabase = self.PlatformInfo.BuildRule\r
828 for Type in BuildRuleDatabase.FileTypeList:\r
829 #first try getting build rule by BuildRuleFamily\r
830 RuleObject = BuildRuleDatabase[Type, self.BuildType, self.Arch, self.BuildRuleFamily]\r
831 if not RuleObject:\r
832 # build type is always module type, but ...\r
833 if self.ModuleType != self.BuildType:\r
834 RuleObject = BuildRuleDatabase[Type, self.ModuleType, self.Arch, self.BuildRuleFamily]\r
835 #second try getting build rule by ToolChainFamily\r
836 if not RuleObject:\r
837 RuleObject = BuildRuleDatabase[Type, self.BuildType, self.Arch, self.ToolChainFamily]\r
838 if not RuleObject:\r
839 # build type is always module type, but ...\r
840 if self.ModuleType != self.BuildType:\r
841 RuleObject = BuildRuleDatabase[Type, self.ModuleType, self.Arch, self.ToolChainFamily]\r
842 if not RuleObject:\r
843 continue\r
844 RuleObject = RuleObject.Instantiate(self.Macros)\r
845 RetVal[Type] = RuleObject\r
846 for Ext in RuleObject.SourceFileExtList:\r
847 RetVal[Ext] = RuleObject\r
848 return RetVal\r
849\r
850 def _ApplyBuildRule(self, File, FileType, BinaryFileList=None):\r
851 if self._BuildTargets is None:\r
852 self._IntroBuildTargetList = set()\r
853 self._FinalBuildTargetList = set()\r
854 self._BuildTargets = defaultdict(set)\r
855 self._FileTypes = defaultdict(set)\r
856\r
857 if not BinaryFileList:\r
858 BinaryFileList = self.BinaryFileList\r
859\r
860 SubDirectory = os.path.join(self.OutputDir, File.SubDir)\r
861 if not os.path.exists(SubDirectory):\r
862 CreateDirectory(SubDirectory)\r
863 LastTarget = None\r
864 RuleChain = set()\r
865 SourceList = [File]\r
866 Index = 0\r
867 #\r
868 # Make sure to get build rule order value\r
869 #\r
870 self.BuildOption\r
871\r
872 while Index < len(SourceList):\r
873 Source = SourceList[Index]\r
874 Index = Index + 1\r
875\r
876 if Source != File:\r
877 CreateDirectory(Source.Dir)\r
878\r
879 if File.IsBinary and File == Source and File in BinaryFileList:\r
880 # Skip all files that are not binary libraries\r
881 if not self.IsLibrary:\r
882 continue\r
883 RuleObject = self.BuildRules[TAB_DEFAULT_BINARY_FILE]\r
884 elif FileType in self.BuildRules:\r
885 RuleObject = self.BuildRules[FileType]\r
886 elif Source.Ext in self.BuildRules:\r
887 RuleObject = self.BuildRules[Source.Ext]\r
888 else:\r
889 # stop at no more rules\r
890 if LastTarget:\r
891 self._FinalBuildTargetList.add(LastTarget)\r
892 break\r
893\r
894 FileType = RuleObject.SourceFileType\r
895 self._FileTypes[FileType].add(Source)\r
896\r
897 # stop at STATIC_LIBRARY for library\r
898 if self.IsLibrary and FileType == TAB_STATIC_LIBRARY:\r
899 if LastTarget:\r
900 self._FinalBuildTargetList.add(LastTarget)\r
901 break\r
902\r
903 Target = RuleObject.Apply(Source, self.BuildRuleOrder)\r
904 if not Target:\r
905 if LastTarget:\r
906 self._FinalBuildTargetList.add(LastTarget)\r
907 break\r
908 elif not Target.Outputs:\r
909 # Only do build for target with outputs\r
910 self._FinalBuildTargetList.add(Target)\r
911\r
912 self._BuildTargets[FileType].add(Target)\r
913\r
914 if not Source.IsBinary and Source == File:\r
915 self._IntroBuildTargetList.add(Target)\r
916\r
917 # to avoid cyclic rule\r
918 if FileType in RuleChain:\r
919 break\r
920\r
921 RuleChain.add(FileType)\r
922 SourceList.extend(Target.Outputs)\r
923 LastTarget = Target\r
924 FileType = TAB_UNKNOWN_FILE\r
925\r
926 @cached_property\r
927 def Targets(self):\r
928 if self._BuildTargets is None:\r
929 self._IntroBuildTargetList = set()\r
930 self._FinalBuildTargetList = set()\r
931 self._BuildTargets = defaultdict(set)\r
932 self._FileTypes = defaultdict(set)\r
933\r
934 #TRICK: call SourceFileList property to apply build rule for source files\r
935 self.SourceFileList\r
936\r
937 #TRICK: call _GetBinaryFileList to apply build rule for binary files\r
938 self.BinaryFileList\r
939\r
940 return self._BuildTargets\r
941\r
942 @cached_property\r
943 def IntroTargetList(self):\r
944 self.Targets\r
945 return self._IntroBuildTargetList\r
946\r
947 @cached_property\r
948 def CodaTargetList(self):\r
949 self.Targets\r
950 return self._FinalBuildTargetList\r
951\r
952 @cached_property\r
953 def FileTypes(self):\r
954 self.Targets\r
955 return self._FileTypes\r
956\r
bf1ea933 957 ## Get the list of package object the module depends on and the Platform depends on\r
e8449e1d
FB
958 #\r
959 # @retval list The package object list\r
960 #\r
961 @cached_property\r
962 def DependentPackageList(self):\r
bf1ea933 963 return self.PackageList\r
e8449e1d
FB
964\r
965 ## Return the list of auto-generated code file\r
966 #\r
967 # @retval list The list of auto-generated file\r
968 #\r
969 @cached_property\r
970 def AutoGenFileList(self):\r
971 AutoGenUniIdf = self.BuildType != 'UEFI_HII'\r
972 UniStringBinBuffer = BytesIO()\r
973 IdfGenBinBuffer = BytesIO()\r
974 RetVal = {}\r
975 AutoGenC = TemplateString()\r
976 AutoGenH = TemplateString()\r
977 StringH = TemplateString()\r
978 StringIdf = TemplateString()\r
979 GenC.CreateCode(self, AutoGenC, AutoGenH, StringH, AutoGenUniIdf, UniStringBinBuffer, StringIdf, AutoGenUniIdf, IdfGenBinBuffer)\r
980 #\r
981 # AutoGen.c is generated if there are library classes in inf, or there are object files\r
982 #\r
983 if str(AutoGenC) != "" and (len(self.Module.LibraryClasses) > 0\r
984 or TAB_OBJECT_FILE in self.FileTypes):\r
985 AutoFile = PathClass(gAutoGenCodeFileName, self.DebugDir)\r
986 RetVal[AutoFile] = str(AutoGenC)\r
987 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
988 if str(AutoGenH) != "":\r
989 AutoFile = PathClass(gAutoGenHeaderFileName, self.DebugDir)\r
990 RetVal[AutoFile] = str(AutoGenH)\r
991 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
992 if str(StringH) != "":\r
993 AutoFile = PathClass(gAutoGenStringFileName % {"module_name":self.Name}, self.DebugDir)\r
994 RetVal[AutoFile] = str(StringH)\r
995 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
996 if UniStringBinBuffer is not None and UniStringBinBuffer.getvalue() != b"":\r
997 AutoFile = PathClass(gAutoGenStringFormFileName % {"module_name":self.Name}, self.OutputDir)\r
998 RetVal[AutoFile] = UniStringBinBuffer.getvalue()\r
999 AutoFile.IsBinary = True\r
1000 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
1001 if UniStringBinBuffer is not None:\r
1002 UniStringBinBuffer.close()\r
1003 if str(StringIdf) != "":\r
1004 AutoFile = PathClass(gAutoGenImageDefFileName % {"module_name":self.Name}, self.DebugDir)\r
1005 RetVal[AutoFile] = str(StringIdf)\r
1006 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
1007 if IdfGenBinBuffer is not None and IdfGenBinBuffer.getvalue() != b"":\r
1008 AutoFile = PathClass(gAutoGenIdfFileName % {"module_name":self.Name}, self.OutputDir)\r
1009 RetVal[AutoFile] = IdfGenBinBuffer.getvalue()\r
1010 AutoFile.IsBinary = True\r
1011 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)\r
1012 if IdfGenBinBuffer is not None:\r
1013 IdfGenBinBuffer.close()\r
1014 return RetVal\r
1015\r
1016 ## Return the list of library modules explicitly or implicitly used by this module\r
1017 @cached_property\r
1018 def DependentLibraryList(self):\r
1019 # only merge library classes and PCD for non-library module\r
1020 if self.IsLibrary:\r
1021 return []\r
1022 return self.PlatformInfo.ApplyLibraryInstance(self.Module)\r
1023\r
1024 ## Get the list of PCDs from current module\r
1025 #\r
1026 # @retval list The list of PCD\r
1027 #\r
1028 @cached_property\r
1029 def ModulePcdList(self):\r
1030 # apply PCD settings from platform\r
1031 RetVal = self.PlatformInfo.ApplyPcdSetting(self.Module, self.Module.Pcds)\r
1032\r
1033 return RetVal\r
1034 @cached_property\r
1035 def _PcdComments(self):\r
1036 ReVal = OrderedListDict()\r
1037 ExtendCopyDictionaryLists(ReVal, self.Module.PcdComments)\r
1038 if not self.IsLibrary:\r
1039 for Library in self.DependentLibraryList:\r
1040 ExtendCopyDictionaryLists(ReVal, Library.PcdComments)\r
1041 return ReVal\r
1042\r
1043 ## Get the list of PCDs from dependent libraries\r
1044 #\r
1045 # @retval list The list of PCD\r
1046 #\r
1047 @cached_property\r
1048 def LibraryPcdList(self):\r
1049 if self.IsLibrary:\r
1050 return []\r
1051 RetVal = []\r
1052 Pcds = set()\r
1053 # get PCDs from dependent libraries\r
1054 for Library in self.DependentLibraryList:\r
1055 PcdsInLibrary = OrderedDict()\r
1056 for Key in Library.Pcds:\r
1057 # skip duplicated PCDs\r
1058 if Key in self.Module.Pcds or Key in Pcds:\r
1059 continue\r
1060 Pcds.add(Key)\r
1061 PcdsInLibrary[Key] = copy.copy(Library.Pcds[Key])\r
1062 RetVal.extend(self.PlatformInfo.ApplyPcdSetting(self.Module, PcdsInLibrary, Library=Library))\r
1063 return RetVal\r
1064\r
1065 ## Get the GUID value mapping\r
1066 #\r
1067 # @retval dict The mapping between GUID cname and its value\r
1068 #\r
1069 @cached_property\r
1070 def GuidList(self):\r
1071 RetVal = self.Module.Guids\r
1072 for Library in self.DependentLibraryList:\r
1073 RetVal.update(Library.Guids)\r
1074 ExtendCopyDictionaryLists(self._GuidComments, Library.GuidComments)\r
1075 ExtendCopyDictionaryLists(self._GuidComments, self.Module.GuidComments)\r
1076 return RetVal\r
1077\r
1078 @cached_property\r
1079 def GetGuidsUsedByPcd(self):\r
1080 RetVal = OrderedDict(self.Module.GetGuidsUsedByPcd())\r
1081 for Library in self.DependentLibraryList:\r
1082 RetVal.update(Library.GetGuidsUsedByPcd())\r
1083 return RetVal\r
1084 ## Get the protocol value mapping\r
1085 #\r
1086 # @retval dict The mapping between protocol cname and its value\r
1087 #\r
1088 @cached_property\r
1089 def ProtocolList(self):\r
1090 RetVal = OrderedDict(self.Module.Protocols)\r
1091 for Library in self.DependentLibraryList:\r
1092 RetVal.update(Library.Protocols)\r
1093 ExtendCopyDictionaryLists(self._ProtocolComments, Library.ProtocolComments)\r
1094 ExtendCopyDictionaryLists(self._ProtocolComments, self.Module.ProtocolComments)\r
1095 return RetVal\r
1096\r
1097 ## Get the PPI value mapping\r
1098 #\r
1099 # @retval dict The mapping between PPI cname and its value\r
1100 #\r
1101 @cached_property\r
1102 def PpiList(self):\r
1103 RetVal = OrderedDict(self.Module.Ppis)\r
1104 for Library in self.DependentLibraryList:\r
1105 RetVal.update(Library.Ppis)\r
1106 ExtendCopyDictionaryLists(self._PpiComments, Library.PpiComments)\r
1107 ExtendCopyDictionaryLists(self._PpiComments, self.Module.PpiComments)\r
1108 return RetVal\r
1109\r
1110 ## Get the list of include search path\r
1111 #\r
1112 # @retval list The list path\r
1113 #\r
1114 @cached_property\r
1115 def IncludePathList(self):\r
1116 RetVal = []\r
1117 RetVal.append(self.MetaFile.Dir)\r
1118 RetVal.append(self.DebugDir)\r
1119\r
bf1ea933 1120 for Package in self.PackageList:\r
e8449e1d
FB
1121 PackageDir = mws.join(self.WorkspaceDir, Package.MetaFile.Dir)\r
1122 if PackageDir not in RetVal:\r
1123 RetVal.append(PackageDir)\r
1124 IncludesList = Package.Includes\r
1125 if Package._PrivateIncludes:\r
1126 if not self.MetaFile.OriginalPath.Path.startswith(PackageDir):\r
1127 IncludesList = list(set(Package.Includes).difference(set(Package._PrivateIncludes)))\r
1128 for Inc in IncludesList:\r
1129 if Inc not in RetVal:\r
1130 RetVal.append(str(Inc))\r
0c3e8e99 1131 RetVal.extend(self.IncPathFromBuildOptions)\r
e8449e1d
FB
1132 return RetVal\r
1133\r
0c3e8e99
BF
1134 @cached_property\r
1135 def IncPathFromBuildOptions(self):\r
1136 IncPathList = []\r
1137 for tool in self.BuildOption:\r
1138 if 'FLAGS' in self.BuildOption[tool]:\r
1139 flags = self.BuildOption[tool]['FLAGS']\r
1140 whitespace = False\r
1141 for flag in flags.split(" "):\r
1142 flag = flag.strip()\r
1143 if flag.startswith(("/I","-I")):\r
1144 if len(flag)>2:\r
1145 if os.path.exists(flag[2:]):\r
1146 IncPathList.append(flag[2:])\r
1147 else:\r
1148 whitespace = True\r
1149 continue\r
1150 if whitespace and flag:\r
1151 if os.path.exists(flag):\r
1152 IncPathList.append(flag)\r
1153 whitespace = False\r
1154 return IncPathList\r
1155\r
e8449e1d
FB
1156 @cached_property\r
1157 def IncludePathLength(self):\r
1158 return sum(len(inc)+1 for inc in self.IncludePathList)\r
1159\r
82407bd1
RC
1160 ## Get the list of include paths from the packages\r
1161 #\r
1162 # @IncludesList list The list path\r
1163 #\r
1164 @cached_property\r
1165 def PackageIncludePathList(self):\r
1166 IncludesList = []\r
bf1ea933 1167 for Package in self.PackageList:\r
82407bd1
RC
1168 PackageDir = mws.join(self.WorkspaceDir, Package.MetaFile.Dir)\r
1169 IncludesList = Package.Includes\r
1170 if Package._PrivateIncludes:\r
1171 if not self.MetaFile.Path.startswith(PackageDir):\r
1172 IncludesList = list(set(Package.Includes).difference(set(Package._PrivateIncludes)))\r
1173 return IncludesList\r
1174\r
e8449e1d
FB
1175 ## Get HII EX PCDs which maybe used by VFR\r
1176 #\r
1177 # efivarstore used by VFR may relate with HII EX PCDs\r
1178 # Get the variable name and GUID from efivarstore and HII EX PCD\r
1179 # List the HII EX PCDs in As Built INF if both name and GUID match.\r
1180 #\r
1181 # @retval list HII EX PCDs\r
1182 #\r
1183 def _GetPcdsMaybeUsedByVfr(self):\r
1184 if not self.SourceFileList:\r
1185 return []\r
1186\r
1187 NameGuids = set()\r
1188 for SrcFile in self.SourceFileList:\r
1189 if SrcFile.Ext.lower() != '.vfr':\r
1190 continue\r
1191 Vfri = os.path.join(self.OutputDir, SrcFile.BaseName + '.i')\r
1192 if not os.path.exists(Vfri):\r
1193 continue\r
1194 VfriFile = open(Vfri, 'r')\r
1195 Content = VfriFile.read()\r
1196 VfriFile.close()\r
1197 Pos = Content.find('efivarstore')\r
1198 while Pos != -1:\r
1199 #\r
1200 # Make sure 'efivarstore' is the start of efivarstore statement\r
1201 # In case of the value of 'name' (name = efivarstore) is equal to 'efivarstore'\r
1202 #\r
1203 Index = Pos - 1\r
1204 while Index >= 0 and Content[Index] in ' \t\r\n':\r
1205 Index -= 1\r
1206 if Index >= 0 and Content[Index] != ';':\r
1207 Pos = Content.find('efivarstore', Pos + len('efivarstore'))\r
1208 continue\r
1209 #\r
1210 # 'efivarstore' must be followed by name and guid\r
1211 #\r
1212 Name = gEfiVarStoreNamePattern.search(Content, Pos)\r
1213 if not Name:\r
1214 break\r
1215 Guid = gEfiVarStoreGuidPattern.search(Content, Pos)\r
1216 if not Guid:\r
1217 break\r
1218 NameArray = _ConvertStringToByteArray('L"' + Name.group(1) + '"')\r
1219 NameGuids.add((NameArray, GuidStructureStringToGuidString(Guid.group(1))))\r
1220 Pos = Content.find('efivarstore', Name.end())\r
1221 if not NameGuids:\r
1222 return []\r
1223 HiiExPcds = []\r
1224 for Pcd in self.PlatformInfo.Pcds.values():\r
1225 if Pcd.Type != TAB_PCDS_DYNAMIC_EX_HII:\r
1226 continue\r
1227 for SkuInfo in Pcd.SkuInfoList.values():\r
1228 Value = GuidValue(SkuInfo.VariableGuid, self.PlatformInfo.PackageList, self.MetaFile.Path)\r
1229 if not Value:\r
1230 continue\r
1231 Name = _ConvertStringToByteArray(SkuInfo.VariableName)\r
1232 Guid = GuidStructureStringToGuidString(Value)\r
1233 if (Name, Guid) in NameGuids and Pcd not in HiiExPcds:\r
1234 HiiExPcds.append(Pcd)\r
1235 break\r
1236\r
1237 return HiiExPcds\r
1238\r
1239 def _GenOffsetBin(self):\r
1240 VfrUniBaseName = {}\r
1241 for SourceFile in self.Module.Sources:\r
1242 if SourceFile.Type.upper() == ".VFR" :\r
1243 #\r
1244 # search the .map file to find the offset of vfr binary in the PE32+/TE file.\r
1245 #\r
1246 VfrUniBaseName[SourceFile.BaseName] = (SourceFile.BaseName + "Bin")\r
1247 elif SourceFile.Type.upper() == ".UNI" :\r
1248 #\r
1249 # search the .map file to find the offset of Uni strings binary in the PE32+/TE file.\r
1250 #\r
1251 VfrUniBaseName["UniOffsetName"] = (self.Name + "Strings")\r
1252\r
1253 if not VfrUniBaseName:\r
1254 return None\r
1255 MapFileName = os.path.join(self.OutputDir, self.Name + ".map")\r
1256 EfiFileName = os.path.join(self.OutputDir, self.Name + ".efi")\r
1257 VfrUniOffsetList = GetVariableOffset(MapFileName, EfiFileName, list(VfrUniBaseName.values()))\r
1258 if not VfrUniOffsetList:\r
1259 return None\r
1260\r
1261 OutputName = '%sOffset.bin' % self.Name\r
1262 UniVfrOffsetFileName = os.path.join( self.OutputDir, OutputName)\r
1263\r
1264 try:\r
1265 fInputfile = open(UniVfrOffsetFileName, "wb+", 0)\r
1266 except:\r
1267 EdkLogger.error("build", FILE_OPEN_FAILURE, "File open failed for %s" % UniVfrOffsetFileName, None)\r
1268\r
1269 # Use a instance of BytesIO to cache data\r
1270 fStringIO = BytesIO()\r
1271\r
1272 for Item in VfrUniOffsetList:\r
1273 if (Item[0].find("Strings") != -1):\r
1274 #\r
1275 # UNI offset in image.\r
1276 # GUID + Offset\r
1277 # { 0x8913c5e0, 0x33f6, 0x4d86, { 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66 } }\r
1278 #\r
1279 UniGuid = b'\xe0\xc5\x13\x89\xf63\x86M\x9b\xf1C\xef\x89\xfc\x06f'\r
1280 fStringIO.write(UniGuid)\r
1281 UniValue = pack ('Q', int (Item[1], 16))\r
1282 fStringIO.write (UniValue)\r
1283 else:\r
1284 #\r
1285 # VFR binary offset in image.\r
1286 # GUID + Offset\r
1287 # { 0xd0bc7cb4, 0x6a47, 0x495f, { 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2 } };\r
1288 #\r
1289 VfrGuid = b'\xb4|\xbc\xd0Gj_I\xaa\x11q\x07F\xda\x06\xa2'\r
1290 fStringIO.write(VfrGuid)\r
1291 VfrValue = pack ('Q', int (Item[1], 16))\r
1292 fStringIO.write (VfrValue)\r
1293 #\r
1294 # write data into file.\r
1295 #\r
1296 try :\r
1297 fInputfile.write (fStringIO.getvalue())\r
1298 except:\r
1299 EdkLogger.error("build", FILE_WRITE_FAILURE, "Write data to file %s failed, please check whether the "\r
1300 "file been locked or using by other applications." %UniVfrOffsetFileName, None)\r
1301\r
1302 fStringIO.close ()\r
1303 fInputfile.close ()\r
1304 return OutputName\r
d01a9986 1305\r
e8449e1d
FB
1306 @cached_property\r
1307 def OutputFile(self):\r
1308 retVal = set()\r
40db176d 1309\r
91f6c533 1310 for Root, Dirs, Files in os.walk(self.BuildDir):\r
e8449e1d 1311 for File in Files:\r
40db176d 1312 # lib file is already added through above CodaTargetList, skip it here\r
91f6c533
SS
1313 if not (File.lower().endswith('.obj') or File.lower().endswith('.debug')):\r
1314 NewFile = path.join(Root, File)\r
40db176d 1315 retVal.add(NewFile)\r
e8449e1d 1316\r
40db176d 1317 for Root, Dirs, Files in os.walk(self.FfsOutputDir):\r
d01a9986 1318 for File in Files:\r
91f6c533 1319 NewFile = path.join(Root, File)\r
40db176d 1320 retVal.add(NewFile)\r
d01a9986 1321\r
e8449e1d
FB
1322 return retVal\r
1323\r
1324 ## Create AsBuilt INF file the module\r
1325 #\r
1326 def CreateAsBuiltInf(self):\r
1327\r
1328 if self.IsAsBuiltInfCreated:\r
1329 return\r
1330\r
1331 # Skip INF file generation for libraries\r
1332 if self.IsLibrary:\r
1333 return\r
1334\r
1335 # Skip the following code for modules with no source files\r
1336 if not self.SourceFileList:\r
1337 return\r
1338\r
1339 # Skip the following code for modules without any binary files\r
1340 if self.BinaryFileList:\r
1341 return\r
1342\r
1343 ### TODO: How to handles mixed source and binary modules\r
1344\r
1345 # Find all DynamicEx and PatchableInModule PCDs used by this module and dependent libraries\r
1346 # Also find all packages that the DynamicEx PCDs depend on\r
1347 Pcds = []\r
1348 PatchablePcds = []\r
1349 Packages = []\r
1350 PcdCheckList = []\r
1351 PcdTokenSpaceList = []\r
1352 for Pcd in self.ModulePcdList + self.LibraryPcdList:\r
1353 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:\r
1354 PatchablePcds.append(Pcd)\r
1355 PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, TAB_PCDS_PATCHABLE_IN_MODULE))\r
1356 elif Pcd.Type in PCD_DYNAMIC_EX_TYPE_SET:\r
1357 if Pcd not in Pcds:\r
1358 Pcds.append(Pcd)\r
1359 PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC_EX))\r
1360 PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC))\r
1361 PcdTokenSpaceList.append(Pcd.TokenSpaceGuidCName)\r
1362 GuidList = OrderedDict(self.GuidList)\r
1363 for TokenSpace in self.GetGuidsUsedByPcd:\r
1364 # If token space is not referred by patch PCD or Ex PCD, remove the GUID from GUID list\r
1365 # The GUIDs in GUIDs section should really be the GUIDs in source INF or referred by Ex an patch PCDs\r
1366 if TokenSpace not in PcdTokenSpaceList and TokenSpace in GuidList:\r
1367 GuidList.pop(TokenSpace)\r
1368 CheckList = (GuidList, self.PpiList, self.ProtocolList, PcdCheckList)\r
1369 for Package in self.DerivedPackageList:\r
1370 if Package in Packages:\r
1371 continue\r
1372 BeChecked = (Package.Guids, Package.Ppis, Package.Protocols, Package.Pcds)\r
1373 Found = False\r
1374 for Index in range(len(BeChecked)):\r
1375 for Item in CheckList[Index]:\r
1376 if Item in BeChecked[Index]:\r
1377 Packages.append(Package)\r
1378 Found = True\r
1379 break\r
1380 if Found:\r
1381 break\r
1382\r
1383 VfrPcds = self._GetPcdsMaybeUsedByVfr()\r
1384 for Pkg in self.PlatformInfo.PackageList:\r
1385 if Pkg in Packages:\r
1386 continue\r
1387 for VfrPcd in VfrPcds:\r
1388 if ((VfrPcd.TokenCName, VfrPcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC_EX) in Pkg.Pcds or\r
1389 (VfrPcd.TokenCName, VfrPcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC) in Pkg.Pcds):\r
1390 Packages.append(Pkg)\r
1391 break\r
1392\r
1393 ModuleType = SUP_MODULE_DXE_DRIVER if self.ModuleType == SUP_MODULE_UEFI_DRIVER and self.DepexGenerated else self.ModuleType\r
1394 DriverType = self.PcdIsDriver if self.PcdIsDriver else ''\r
1395 Guid = self.Guid\r
1396 MDefs = self.Module.Defines\r
1397\r
1398 AsBuiltInfDict = {\r
1399 'module_name' : self.Name,\r
1400 'module_guid' : Guid,\r
1401 'module_module_type' : ModuleType,\r
1402 'module_version_string' : [MDefs['VERSION_STRING']] if 'VERSION_STRING' in MDefs else [],\r
1403 'pcd_is_driver_string' : [],\r
1404 'module_uefi_specification_version' : [],\r
1405 'module_pi_specification_version' : [],\r
1406 'module_entry_point' : self.Module.ModuleEntryPointList,\r
1407 'module_unload_image' : self.Module.ModuleUnloadImageList,\r
1408 'module_constructor' : self.Module.ConstructorList,\r
1409 'module_destructor' : self.Module.DestructorList,\r
1410 'module_shadow' : [MDefs['SHADOW']] if 'SHADOW' in MDefs else [],\r
1411 'module_pci_vendor_id' : [MDefs['PCI_VENDOR_ID']] if 'PCI_VENDOR_ID' in MDefs else [],\r
1412 'module_pci_device_id' : [MDefs['PCI_DEVICE_ID']] if 'PCI_DEVICE_ID' in MDefs else [],\r
1413 'module_pci_class_code' : [MDefs['PCI_CLASS_CODE']] if 'PCI_CLASS_CODE' in MDefs else [],\r
1414 'module_pci_revision' : [MDefs['PCI_REVISION']] if 'PCI_REVISION' in MDefs else [],\r
1415 'module_build_number' : [MDefs['BUILD_NUMBER']] if 'BUILD_NUMBER' in MDefs else [],\r
1416 'module_spec' : [MDefs['SPEC']] if 'SPEC' in MDefs else [],\r
1417 'module_uefi_hii_resource_section' : [MDefs['UEFI_HII_RESOURCE_SECTION']] if 'UEFI_HII_RESOURCE_SECTION' in MDefs else [],\r
1418 'module_uni_file' : [MDefs['MODULE_UNI_FILE']] if 'MODULE_UNI_FILE' in MDefs else [],\r
1419 'module_arch' : self.Arch,\r
1420 'package_item' : [Package.MetaFile.File.replace('\\', '/') for Package in Packages],\r
1421 'binary_item' : [],\r
1422 'patchablepcd_item' : [],\r
1423 'pcd_item' : [],\r
1424 'protocol_item' : [],\r
1425 'ppi_item' : [],\r
1426 'guid_item' : [],\r
1427 'flags_item' : [],\r
1428 'libraryclasses_item' : []\r
1429 }\r
1430\r
1431 if 'MODULE_UNI_FILE' in MDefs:\r
1432 UNIFile = os.path.join(self.MetaFile.Dir, MDefs['MODULE_UNI_FILE'])\r
1433 if os.path.isfile(UNIFile):\r
1434 shutil.copy2(UNIFile, self.OutputDir)\r
1435\r
1436 if self.AutoGenVersion > int(gInfSpecVersion, 0):\r
1437 AsBuiltInfDict['module_inf_version'] = '0x%08x' % self.AutoGenVersion\r
1438 else:\r
1439 AsBuiltInfDict['module_inf_version'] = gInfSpecVersion\r
1440\r
1441 if DriverType:\r
1442 AsBuiltInfDict['pcd_is_driver_string'].append(DriverType)\r
1443\r
1444 if 'UEFI_SPECIFICATION_VERSION' in self.Specification:\r
1445 AsBuiltInfDict['module_uefi_specification_version'].append(self.Specification['UEFI_SPECIFICATION_VERSION'])\r
1446 if 'PI_SPECIFICATION_VERSION' in self.Specification:\r
1447 AsBuiltInfDict['module_pi_specification_version'].append(self.Specification['PI_SPECIFICATION_VERSION'])\r
1448\r
1449 OutputDir = self.OutputDir.replace('\\', '/').strip('/')\r
1450 DebugDir = self.DebugDir.replace('\\', '/').strip('/')\r
1451 for Item in self.CodaTargetList:\r
1452 File = Item.Target.Path.replace('\\', '/').strip('/').replace(DebugDir, '').replace(OutputDir, '').strip('/')\r
1453 if os.path.isabs(File):\r
1454 File = File.replace('\\', '/').strip('/').replace(OutputDir, '').strip('/')\r
1455 if Item.Target.Ext.lower() == '.aml':\r
1456 AsBuiltInfDict['binary_item'].append('ASL|' + File)\r
1457 elif Item.Target.Ext.lower() == '.acpi':\r
1458 AsBuiltInfDict['binary_item'].append('ACPI|' + File)\r
1459 elif Item.Target.Ext.lower() == '.efi':\r
1460 AsBuiltInfDict['binary_item'].append('PE32|' + self.Name + '.efi')\r
1461 else:\r
1462 AsBuiltInfDict['binary_item'].append('BIN|' + File)\r
1463 if not self.DepexGenerated:\r
1464 DepexFile = os.path.join(self.OutputDir, self.Name + '.depex')\r
1465 if os.path.exists(DepexFile):\r
1466 self.DepexGenerated = True\r
1467 if self.DepexGenerated:\r
1468 if self.ModuleType in [SUP_MODULE_PEIM]:\r
1469 AsBuiltInfDict['binary_item'].append('PEI_DEPEX|' + self.Name + '.depex')\r
1470 elif self.ModuleType in [SUP_MODULE_DXE_DRIVER, SUP_MODULE_DXE_RUNTIME_DRIVER, SUP_MODULE_DXE_SAL_DRIVER, SUP_MODULE_UEFI_DRIVER]:\r
1471 AsBuiltInfDict['binary_item'].append('DXE_DEPEX|' + self.Name + '.depex')\r
1472 elif self.ModuleType in [SUP_MODULE_DXE_SMM_DRIVER]:\r
1473 AsBuiltInfDict['binary_item'].append('SMM_DEPEX|' + self.Name + '.depex')\r
1474\r
1475 Bin = self._GenOffsetBin()\r
1476 if Bin:\r
1477 AsBuiltInfDict['binary_item'].append('BIN|%s' % Bin)\r
1478\r
1479 for Root, Dirs, Files in os.walk(OutputDir):\r
1480 for File in Files:\r
1481 if File.lower().endswith('.pdb'):\r
1482 AsBuiltInfDict['binary_item'].append('DISPOSABLE|' + File)\r
1483 HeaderComments = self.Module.HeaderComments\r
1484 StartPos = 0\r
1485 for Index in range(len(HeaderComments)):\r
1486 if HeaderComments[Index].find('@BinaryHeader') != -1:\r
1487 HeaderComments[Index] = HeaderComments[Index].replace('@BinaryHeader', '@file')\r
1488 StartPos = Index\r
1489 break\r
1490 AsBuiltInfDict['header_comments'] = '\n'.join(HeaderComments[StartPos:]).replace(':#', '://')\r
1491 AsBuiltInfDict['tail_comments'] = '\n'.join(self.Module.TailComments)\r
1492\r
1493 GenList = [\r
1494 (self.ProtocolList, self._ProtocolComments, 'protocol_item'),\r
1495 (self.PpiList, self._PpiComments, 'ppi_item'),\r
1496 (GuidList, self._GuidComments, 'guid_item')\r
1497 ]\r
1498 for Item in GenList:\r
1499 for CName in Item[0]:\r
1500 Comments = '\n '.join(Item[1][CName]) if CName in Item[1] else ''\r
1501 Entry = Comments + '\n ' + CName if Comments else CName\r
1502 AsBuiltInfDict[Item[2]].append(Entry)\r
1503 PatchList = parsePcdInfoFromMapFile(\r
1504 os.path.join(self.OutputDir, self.Name + '.map'),\r
1505 os.path.join(self.OutputDir, self.Name + '.efi')\r
1506 )\r
1507 if PatchList:\r
1508 for Pcd in PatchablePcds:\r
1509 TokenCName = Pcd.TokenCName\r
1510 for PcdItem in GlobalData.MixedPcd:\r
1511 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:\r
1512 TokenCName = PcdItem[0]\r
1513 break\r
1514 for PatchPcd in PatchList:\r
1515 if TokenCName == PatchPcd[0]:\r
1516 break\r
1517 else:\r
1518 continue\r
1519 PcdValue = ''\r
1520 if Pcd.DatumType == 'BOOLEAN':\r
1521 BoolValue = Pcd.DefaultValue.upper()\r
1522 if BoolValue == 'TRUE':\r
1523 Pcd.DefaultValue = '1'\r
1524 elif BoolValue == 'FALSE':\r
1525 Pcd.DefaultValue = '0'\r
1526\r
1527 if Pcd.DatumType in TAB_PCD_NUMERIC_TYPES:\r
1528 HexFormat = '0x%02x'\r
1529 if Pcd.DatumType == TAB_UINT16:\r
1530 HexFormat = '0x%04x'\r
1531 elif Pcd.DatumType == TAB_UINT32:\r
1532 HexFormat = '0x%08x'\r
1533 elif Pcd.DatumType == TAB_UINT64:\r
1534 HexFormat = '0x%016x'\r
1535 PcdValue = HexFormat % int(Pcd.DefaultValue, 0)\r
1536 else:\r
1537 if Pcd.MaxDatumSize is None or Pcd.MaxDatumSize == '':\r
1538 EdkLogger.error("build", AUTOGEN_ERROR,\r
1539 "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd.TokenSpaceGuidCName, TokenCName)\r
1540 )\r
1541 ArraySize = int(Pcd.MaxDatumSize, 0)\r
1542 PcdValue = Pcd.DefaultValue\r
1543 if PcdValue[0] != '{':\r
1544 Unicode = False\r
1545 if PcdValue[0] == 'L':\r
1546 Unicode = True\r
1547 PcdValue = PcdValue.lstrip('L')\r
1548 PcdValue = eval(PcdValue)\r
1549 NewValue = '{'\r
1550 for Index in range(0, len(PcdValue)):\r
1551 if Unicode:\r
1552 CharVal = ord(PcdValue[Index])\r
1553 NewValue = NewValue + '0x%02x' % (CharVal & 0x00FF) + ', ' \\r
1554 + '0x%02x' % (CharVal >> 8) + ', '\r
1555 else:\r
1556 NewValue = NewValue + '0x%02x' % (ord(PcdValue[Index]) % 0x100) + ', '\r
1557 Padding = '0x00, '\r
1558 if Unicode:\r
1559 Padding = Padding * 2\r
1560 ArraySize = ArraySize // 2\r
1561 if ArraySize < (len(PcdValue) + 1):\r
1562 if Pcd.MaxSizeUserSet:\r
1563 EdkLogger.error("build", AUTOGEN_ERROR,\r
1564 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd.TokenSpaceGuidCName, TokenCName)\r
1565 )\r
1566 else:\r
1567 ArraySize = len(PcdValue) + 1\r
1568 if ArraySize > len(PcdValue) + 1:\r
1569 NewValue = NewValue + Padding * (ArraySize - len(PcdValue) - 1)\r
1570 PcdValue = NewValue + Padding.strip().rstrip(',') + '}'\r
1571 elif len(PcdValue.split(',')) <= ArraySize:\r
1572 PcdValue = PcdValue.rstrip('}') + ', 0x00' * (ArraySize - len(PcdValue.split(',')))\r
1573 PcdValue += '}'\r
1574 else:\r
1575 if Pcd.MaxSizeUserSet:\r
1576 EdkLogger.error("build", AUTOGEN_ERROR,\r
1577 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd.TokenSpaceGuidCName, TokenCName)\r
1578 )\r
1579 else:\r
1580 ArraySize = len(PcdValue) + 1\r
1581 PcdItem = '%s.%s|%s|0x%X' % \\r
1582 (Pcd.TokenSpaceGuidCName, TokenCName, PcdValue, PatchPcd[1])\r
1583 PcdComments = ''\r
1584 if (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in self._PcdComments:\r
1585 PcdComments = '\n '.join(self._PcdComments[Pcd.TokenSpaceGuidCName, Pcd.TokenCName])\r
1586 if PcdComments:\r
1587 PcdItem = PcdComments + '\n ' + PcdItem\r
1588 AsBuiltInfDict['patchablepcd_item'].append(PcdItem)\r
1589\r
1590 for Pcd in Pcds + VfrPcds:\r
1591 PcdCommentList = []\r
1592 HiiInfo = ''\r
1593 TokenCName = Pcd.TokenCName\r
1594 for PcdItem in GlobalData.MixedPcd:\r
1595 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:\r
1596 TokenCName = PcdItem[0]\r
1597 break\r
1598 if Pcd.Type == TAB_PCDS_DYNAMIC_EX_HII:\r
1599 for SkuName in Pcd.SkuInfoList:\r
1600 SkuInfo = Pcd.SkuInfoList[SkuName]\r
1601 HiiInfo = '## %s|%s|%s' % (SkuInfo.VariableName, SkuInfo.VariableGuid, SkuInfo.VariableOffset)\r
1602 break\r
1603 if (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in self._PcdComments:\r
1604 PcdCommentList = self._PcdComments[Pcd.TokenSpaceGuidCName, Pcd.TokenCName][:]\r
1605 if HiiInfo:\r
1606 UsageIndex = -1\r
1607 UsageStr = ''\r
1608 for Index, Comment in enumerate(PcdCommentList):\r
1609 for Usage in UsageList:\r
1610 if Comment.find(Usage) != -1:\r
1611 UsageStr = Usage\r
1612 UsageIndex = Index\r
1613 break\r
1614 if UsageIndex != -1:\r
1615 PcdCommentList[UsageIndex] = '## %s %s %s' % (UsageStr, HiiInfo, PcdCommentList[UsageIndex].replace(UsageStr, ''))\r
1616 else:\r
1617 PcdCommentList.append('## UNDEFINED ' + HiiInfo)\r
1618 PcdComments = '\n '.join(PcdCommentList)\r
1619 PcdEntry = Pcd.TokenSpaceGuidCName + '.' + TokenCName\r
1620 if PcdComments:\r
1621 PcdEntry = PcdComments + '\n ' + PcdEntry\r
1622 AsBuiltInfDict['pcd_item'].append(PcdEntry)\r
1623 for Item in self.BuildOption:\r
1624 if 'FLAGS' in self.BuildOption[Item]:\r
1625 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
1626\r
1627 # Generated LibraryClasses section in comments.\r
1628 for Library in self.LibraryAutoGenList:\r
1629 AsBuiltInfDict['libraryclasses_item'].append(Library.MetaFile.File.replace('\\', '/'))\r
1630\r
1631 # Generated UserExtensions TianoCore section.\r
1632 # All tianocore user extensions are copied.\r
1633 UserExtStr = ''\r
1634 for TianoCore in self._GetTianoCoreUserExtensionList():\r
1635 UserExtStr += '\n'.join(TianoCore)\r
1636 ExtensionFile = os.path.join(self.MetaFile.Dir, TianoCore[1])\r
1637 if os.path.isfile(ExtensionFile):\r
1638 shutil.copy2(ExtensionFile, self.OutputDir)\r
1639 AsBuiltInfDict['userextension_tianocore_item'] = UserExtStr\r
1640\r
1641 # Generated depex expression section in comments.\r
1642 DepexExpression = self._GetDepexExpresionString()\r
1643 AsBuiltInfDict['depexsection_item'] = DepexExpression if DepexExpression else ''\r
1644\r
1645 AsBuiltInf = TemplateString()\r
1646 AsBuiltInf.Append(gAsBuiltInfHeaderString.Replace(AsBuiltInfDict))\r
1647\r
1648 SaveFileOnChange(os.path.join(self.OutputDir, self.Name + '.inf'), str(AsBuiltInf), False)\r
1649\r
1650 self.IsAsBuiltInfCreated = True\r
1651\r
3bfbc915 1652 def CacheCopyFile(self, DestDir, SourceDir, File):\r
fc8b8dea
SS
1653 if os.path.isdir(File):\r
1654 return\r
1655\r
3bfbc915
SS
1656 sub_dir = os.path.relpath(File, SourceDir)\r
1657 destination_file = os.path.join(DestDir, sub_dir)\r
0e7e7a26
SS
1658 destination_dir = os.path.dirname(destination_file)\r
1659 CreateDirectory(destination_dir)\r
1660 try:\r
1661 CopyFileOnChange(File, destination_dir)\r
1662 except:\r
1663 EdkLogger.quiet("[cache warning]: fail to copy file:%s to folder:%s" % (File, destination_dir))\r
1664 return\r
1665\r
e8449e1d 1666 def CopyModuleToCache(self):\r
fc8b8dea
SS
1667 # Find the MakeHashStr and PreMakeHashStr from latest MakeHashFileList\r
1668 # and PreMakeHashFileList files\r
1669 MakeHashStr = None\r
1670 PreMakeHashStr = None\r
1671 MakeTimeStamp = 0\r
1672 PreMakeTimeStamp = 0\r
1673 Files = [f for f in os.listdir(LongFilePath(self.BuildDir)) if path.isfile(LongFilePath(path.join(self.BuildDir, f)))]\r
1674 for File in Files:\r
1675 if ".MakeHashFileList." in File:\r
1676 #find lastest file through time stamp\r
1677 FileTimeStamp = os.stat(LongFilePath(path.join(self.BuildDir, File)))[8]\r
1678 if FileTimeStamp > MakeTimeStamp:\r
1679 MakeTimeStamp = FileTimeStamp\r
1680 MakeHashStr = File.split('.')[-1]\r
1681 if len(MakeHashStr) != 32:\r
1682 EdkLogger.quiet("[cache error]: wrong MakeHashFileList file:%s" % (File))\r
1683 if ".PreMakeHashFileList." in File:\r
1684 FileTimeStamp = os.stat(LongFilePath(path.join(self.BuildDir, File)))[8]\r
1685 if FileTimeStamp > PreMakeTimeStamp:\r
1686 PreMakeTimeStamp = FileTimeStamp\r
1687 PreMakeHashStr = File.split('.')[-1]\r
1688 if len(PreMakeHashStr) != 32:\r
1689 EdkLogger.quiet("[cache error]: wrong PreMakeHashFileList file:%s" % (File))\r
0e7e7a26 1690\r
fc8b8dea
SS
1691 if not MakeHashStr:\r
1692 EdkLogger.quiet("[cache error]: No MakeHashFileList file for module:%s[%s]" % (self.MetaFile.Path, self.Arch))\r
1693 return\r
1694 if not PreMakeHashStr:\r
1695 EdkLogger.quiet("[cache error]: No PreMakeHashFileList file for module:%s[%s]" % (self.MetaFile.Path, self.Arch))\r
1696 return\r
0e7e7a26 1697\r
fc8b8dea
SS
1698 # Create Cache destination dirs\r
1699 FileDir = path.join(GlobalData.gBinCacheDest, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, self.Arch, self.SourceDir, self.MetaFile.BaseName)\r
1700 FfsDir = path.join(GlobalData.gBinCacheDest, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, TAB_FV_DIRECTORY, "Ffs", self.Guid + self.Name)\r
1701 CacheFileDir = path.join(FileDir, MakeHashStr)\r
1702 CacheFfsDir = path.join(FfsDir, MakeHashStr)\r
1703 CreateDirectory (CacheFileDir)\r
1704 CreateDirectory (CacheFfsDir)\r
0e7e7a26 1705\r
fc8b8dea
SS
1706 # Create ModuleHashPair file to support multiple version cache together\r
1707 ModuleHashPair = path.join(FileDir, self.Name + ".ModuleHashPair")\r
1708 ModuleHashPairList = [] # tuple list: [tuple(PreMakefileHash, MakeHash)]\r
1709 if os.path.exists(ModuleHashPair):\r
1710 with open(ModuleHashPair, 'r') as f:\r
1711 ModuleHashPairList = json.load(f)\r
1712 if not (PreMakeHashStr, MakeHashStr) in set(map(tuple, ModuleHashPairList)):\r
1713 ModuleHashPairList.insert(0, (PreMakeHashStr, MakeHashStr))\r
1714 with open(ModuleHashPair, 'w') as f:\r
1715 json.dump(ModuleHashPairList, f, indent=2)\r
1716\r
1717 # Copy files to Cache destination dirs\r
e8449e1d
FB
1718 if not self.OutputFile:\r
1719 Ma = self.BuildDatabase[self.MetaFile, self.Arch, self.BuildTarget, self.ToolChain]\r
1720 self.OutputFile = Ma.Binaries\r
1721 for File in self.OutputFile:\r
fc8b8dea
SS
1722 if File.startswith(os.path.abspath(self.FfsOutputDir)+os.sep):\r
1723 self.CacheCopyFile(CacheFfsDir, self.FfsOutputDir, File)\r
1724 else:\r
1725 if self.Name + ".autogen.hash." in File or \\r
1726 self.Name + ".autogen.hashchain." in File or \\r
1727 self.Name + ".hash." in File or \\r
1728 self.Name + ".hashchain." in File or \\r
1729 self.Name + ".PreMakeHashFileList." in File or \\r
1730 self.Name + ".MakeHashFileList." in File:\r
1731 self.CacheCopyFile(FileDir, self.BuildDir, File)\r
d01a9986 1732 else:\r
fc8b8dea 1733 self.CacheCopyFile(CacheFileDir, self.BuildDir, File)\r
e8449e1d
FB
1734 ## Create makefile for the module and its dependent libraries\r
1735 #\r
1736 # @param CreateLibraryMakeFile Flag indicating if or not the makefiles of\r
1737 # dependent libraries will be created\r
1738 #\r
1739 @cached_class_function\r
1740 def CreateMakeFile(self, CreateLibraryMakeFile=True, GenFfsList = []):\r
0e7e7a26 1741\r
e8449e1d
FB
1742 # nest this function inside it's only caller.\r
1743 def CreateTimeStamp():\r
1744 FileSet = {self.MetaFile.Path}\r
1745\r
1746 for SourceFile in self.Module.Sources:\r
1747 FileSet.add (SourceFile.Path)\r
1748\r
1749 for Lib in self.DependentLibraryList:\r
1750 FileSet.add (Lib.MetaFile.Path)\r
1751\r
1752 for f in self.AutoGenDepSet:\r
1753 FileSet.add (f.Path)\r
1754\r
1755 if os.path.exists (self.TimeStampPath):\r
1756 os.remove (self.TimeStampPath)\r
df43ea6c
FB
1757\r
1758 SaveFileOnChange(self.TimeStampPath, "\n".join(FileSet), False)\r
e8449e1d
FB
1759\r
1760 # Ignore generating makefile when it is a binary module\r
1761 if self.IsBinaryModule:\r
1762 return\r
1763\r
1764 self.GenFfsList = GenFfsList\r
1765\r
1766 if not self.IsLibrary and CreateLibraryMakeFile:\r
1767 for LibraryAutoGen in self.LibraryAutoGenList:\r
1768 LibraryAutoGen.CreateMakeFile()\r
673d09a2 1769\r
0e7e7a26
SS
1770 # CanSkip uses timestamps to determine build skipping\r
1771 if self.CanSkip():\r
e8449e1d
FB
1772 return\r
1773\r
1774 if len(self.CustomMakefile) == 0:\r
1775 Makefile = GenMake.ModuleMakefile(self)\r
1776 else:\r
1777 Makefile = GenMake.CustomMakefile(self)\r
1778 if Makefile.Generate():\r
1779 EdkLogger.debug(EdkLogger.DEBUG_9, "Generated makefile for module %s [%s]" %\r
1780 (self.Name, self.Arch))\r
1781 else:\r
1782 EdkLogger.debug(EdkLogger.DEBUG_9, "Skipped the generation of makefile for module %s [%s]" %\r
1783 (self.Name, self.Arch))\r
1784\r
1785 CreateTimeStamp()\r
1786\r
0e7e7a26
SS
1787 MakefileType = Makefile._FileType\r
1788 MakefileName = Makefile._FILE_NAME_[MakefileType]\r
1789 MakefilePath = os.path.join(self.MakeFileDir, MakefileName)\r
fc8b8dea
SS
1790 FilePath = path.join(self.BuildDir, self.Name + ".makefile")\r
1791 SaveFileOnChange(FilePath, MakefilePath, False)\r
0e7e7a26 1792\r
e8449e1d
FB
1793 def CopyBinaryFiles(self):\r
1794 for File in self.Module.Binaries:\r
1795 SrcPath = File.Path\r
1796 DstPath = os.path.join(self.OutputDir, os.path.basename(SrcPath))\r
1797 CopyLongFilePath(SrcPath, DstPath)\r
1798 ## Create autogen code for the module and its dependent libraries\r
1799 #\r
1800 # @param CreateLibraryCodeFile Flag indicating if or not the code of\r
1801 # dependent libraries will be created\r
1802 #\r
1803 def CreateCodeFile(self, CreateLibraryCodeFile=True):\r
0e7e7a26 1804\r
e8449e1d
FB
1805 if self.IsCodeFileCreated:\r
1806 return\r
1807\r
1808 # Need to generate PcdDatabase even PcdDriver is binarymodule\r
1809 if self.IsBinaryModule and self.PcdIsDriver != '':\r
1810 CreatePcdDatabaseCode(self, TemplateString(), TemplateString())\r
1811 return\r
1812 if self.IsBinaryModule:\r
1813 if self.IsLibrary:\r
1814 self.CopyBinaryFiles()\r
1815 return\r
1816\r
1817 if not self.IsLibrary and CreateLibraryCodeFile:\r
1818 for LibraryAutoGen in self.LibraryAutoGenList:\r
1819 LibraryAutoGen.CreateCodeFile()\r
0e7e7a26
SS
1820\r
1821 # CanSkip uses timestamps to determine build skipping\r
1822 if self.CanSkip():\r
e8449e1d 1823 return\r
1f5e4d91 1824 self.LibraryAutoGenList\r
e8449e1d
FB
1825 AutoGenList = []\r
1826 IgoredAutoGenList = []\r
1827\r
1828 for File in self.AutoGenFileList:\r
1829 if GenC.Generate(File.Path, self.AutoGenFileList[File], File.IsBinary):\r
1830 AutoGenList.append(str(File))\r
1831 else:\r
1832 IgoredAutoGenList.append(str(File))\r
1833\r
1834\r
1835 for ModuleType in self.DepexList:\r
1836 # Ignore empty [depex] section or [depex] section for SUP_MODULE_USER_DEFINED module\r
1837 if len(self.DepexList[ModuleType]) == 0 or ModuleType == SUP_MODULE_USER_DEFINED or ModuleType == SUP_MODULE_HOST_APPLICATION:\r
1838 continue\r
1839\r
1840 Dpx = GenDepex.DependencyExpression(self.DepexList[ModuleType], ModuleType, True)\r
1841 DpxFile = gAutoGenDepexFileName % {"module_name" : self.Name}\r
1842\r
1843 if len(Dpx.PostfixNotation) != 0:\r
1844 self.DepexGenerated = True\r
1845\r
1846 if Dpx.Generate(path.join(self.OutputDir, DpxFile)):\r
1847 AutoGenList.append(str(DpxFile))\r
1848 else:\r
1849 IgoredAutoGenList.append(str(DpxFile))\r
1850\r
1851 if IgoredAutoGenList == []:\r
1852 EdkLogger.debug(EdkLogger.DEBUG_9, "Generated [%s] files for module %s [%s]" %\r
1853 (" ".join(AutoGenList), self.Name, self.Arch))\r
1854 elif AutoGenList == []:\r
1855 EdkLogger.debug(EdkLogger.DEBUG_9, "Skipped the generation of [%s] files for module %s [%s]" %\r
1856 (" ".join(IgoredAutoGenList), self.Name, self.Arch))\r
1857 else:\r
1858 EdkLogger.debug(EdkLogger.DEBUG_9, "Generated [%s] (skipped %s) files for module %s [%s]" %\r
1859 (" ".join(AutoGenList), " ".join(IgoredAutoGenList), self.Name, self.Arch))\r
1860\r
1861 self.IsCodeFileCreated = True\r
0e7e7a26 1862\r
e8449e1d
FB
1863 return AutoGenList\r
1864\r
1865 ## Summarize the ModuleAutoGen objects of all libraries used by this module\r
1866 @cached_property\r
1867 def LibraryAutoGenList(self):\r
1868 RetVal = []\r
1869 for Library in self.DependentLibraryList:\r
1870 La = ModuleAutoGen(\r
1871 self.Workspace,\r
1872 Library.MetaFile,\r
1873 self.BuildTarget,\r
1874 self.ToolChain,\r
1875 self.Arch,\r
1876 self.PlatformInfo.MetaFile,\r
1877 self.DataPipe\r
1878 )\r
1879 La.IsLibrary = True\r
1880 if La not in RetVal:\r
1881 RetVal.append(La)\r
1882 for Lib in La.CodaTargetList:\r
1883 self._ApplyBuildRule(Lib.Target, TAB_UNKNOWN_FILE)\r
1884 return RetVal\r
1885\r
fc8b8dea
SS
1886 def GenCMakeHash(self):\r
1887 # GenCMakeHash can only be called in --binary-destination\r
1888 # Never called in multiprocessing and always directly save result in main process,\r
1889 # so no need remote dict to share the gCMakeHashFile result with main process\r
e8449e1d 1890\r
fc8b8dea
SS
1891 DependencyFileSet = set()\r
1892 # Add AutoGen files\r
1893 if self.AutoGenFileList:\r
1894 for File in set(self.AutoGenFileList):\r
1895 DependencyFileSet.add(File)\r
1896\r
1897 # Add Makefile\r
1898 abspath = path.join(self.BuildDir, self.Name + ".makefile")\r
1899 try:\r
1900 with open(LongFilePath(abspath),"r") as fd:\r
1901 lines = fd.readlines()\r
1902 except Exception as e:\r
1903 EdkLogger.error("build",FILE_NOT_FOUND, "%s doesn't exist" % abspath, ExtraData=str(e), RaiseError=False)\r
1904 if lines:\r
1905 DependencyFileSet.update(lines)\r
e8449e1d 1906\r
fc8b8dea 1907 # Caculate all above dependency files hash\r
e8449e1d 1908 # Initialze hash object\r
fc8b8dea 1909 FileList = []\r
e8449e1d 1910 m = hashlib.md5()\r
fc8b8dea
SS
1911 for File in sorted(DependencyFileSet, key=lambda x: str(x)):\r
1912 if not path.exists(LongFilePath(str(File))):\r
1913 EdkLogger.quiet("[cache warning]: header file %s is missing for module: %s[%s]" % (File, self.MetaFile.Path, self.Arch))\r
1914 continue\r
1915 with open(LongFilePath(str(File)), 'rb') as f:\r
e8449e1d 1916 Content = f.read()\r
fc8b8dea
SS
1917 m.update(Content)\r
1918 FileList.append((str(File), hashlib.md5(Content).hexdigest()))\r
e8449e1d 1919\r
fc8b8dea
SS
1920 HashChainFile = path.join(self.BuildDir, self.Name + ".autogen.hashchain." + m.hexdigest())\r
1921 GlobalData.gCMakeHashFile[(self.MetaFile.Path, self.Arch)] = HashChainFile\r
1922 try:\r
1923 with open(LongFilePath(HashChainFile), 'w') as f:\r
1924 json.dump(FileList, f, indent=2)\r
1925 except:\r
1926 EdkLogger.quiet("[cache warning]: fail to save hashchain file:%s" % HashChainFile)\r
1927 return False\r
0e7e7a26 1928\r
fc8b8dea
SS
1929 def GenModuleHash(self):\r
1930 # GenModuleHash only called after autogen phase\r
1931 # Never called in multiprocessing and always directly save result in main process,\r
1932 # so no need remote dict to share the gModuleHashFile result with main process\r
1933 #\r
1934 # GenPreMakefileHashList consume no dict.\r
1935 # GenPreMakefileHashList produce local gModuleHashFile dict.\r
94459080 1936\r
0e7e7a26
SS
1937 DependencyFileSet = set()\r
1938 # Add Module Meta file\r
fc8b8dea 1939 DependencyFileSet.add(self.MetaFile.Path)\r
0e7e7a26
SS
1940\r
1941 # Add Module's source files\r
1942 if self.SourceFileList:\r
1943 for File in set(self.SourceFileList):\r
fc8b8dea 1944 DependencyFileSet.add(File.Path)\r
0e7e7a26
SS
1945\r
1946 # Add modules's include header files\r
fc8b8dea
SS
1947 # Directly use the deps.txt file in the module BuildDir\r
1948 abspath = path.join(self.BuildDir, "deps.txt")\r
1949 rt = None\r
1950 try:\r
1951 with open(LongFilePath(abspath),"r") as fd:\r
1952 lines = fd.readlines()\r
1953 if lines:\r
1954 rt = set([item.lstrip().strip("\n") for item in lines if item.strip("\n").endswith(".h")])\r
1955 except Exception as e:\r
1956 EdkLogger.error("build",FILE_NOT_FOUND, "%s doesn't exist" % abspath, ExtraData=str(e), RaiseError=False)\r
1957\r
1958 if rt:\r
1959 DependencyFileSet.update(rt)\r
0e7e7a26 1960\r
0e7e7a26
SS
1961\r
1962 # Caculate all above dependency files hash\r
1963 # Initialze hash object\r
1964 FileList = []\r
1965 m = hashlib.md5()\r
fc8b8dea 1966 BuildDirStr = path.abspath(self.BuildDir).lower()\r
0e7e7a26 1967 for File in sorted(DependencyFileSet, key=lambda x: str(x)):\r
fc8b8dea
SS
1968 # Skip the AutoGen files in BuildDir which already been\r
1969 # included in .autogen.hash. file\r
1970 if BuildDirStr in path.abspath(File).lower():\r
1971 continue\r
1972 if not path.exists(LongFilePath(File)):\r
0e7e7a26
SS
1973 EdkLogger.quiet("[cache warning]: header file %s is missing for module: %s[%s]" % (File, self.MetaFile.Path, self.Arch))\r
1974 continue\r
fc8b8dea 1975 with open(LongFilePath(File), 'rb') as f:\r
94459080 1976 Content = f.read()\r
0e7e7a26 1977 m.update(Content)\r
fc8b8dea 1978 FileList.append((File, hashlib.md5(Content).hexdigest()))\r
0e7e7a26 1979\r
fc8b8dea
SS
1980 HashChainFile = path.join(self.BuildDir, self.Name + ".hashchain." + m.hexdigest())\r
1981 GlobalData.gModuleHashFile[(self.MetaFile.Path, self.Arch)] = HashChainFile\r
1982 try:\r
1983 with open(LongFilePath(HashChainFile), 'w') as f:\r
1984 json.dump(FileList, f, indent=2)\r
1985 except:\r
1986 EdkLogger.quiet("[cache warning]: fail to save hashchain file:%s" % HashChainFile)\r
1987 return False\r
0e7e7a26 1988\r
fc8b8dea
SS
1989 def GenPreMakefileHashList(self):\r
1990 # GenPreMakefileHashList consume below dicts:\r
1991 # gPlatformHashFile\r
1992 # gPackageHashFile\r
1993 # gModuleHashFile\r
1994 # GenPreMakefileHashList produce no dict.\r
1995 # gModuleHashFile items might be produced in multiprocessing, so\r
1996 # need check gModuleHashFile remote dict\r
94459080 1997\r
0e7e7a26
SS
1998 # skip binary module\r
1999 if self.IsBinaryModule:\r
2000 return\r
2001\r
fc8b8dea 2002 FileList = []\r
0e7e7a26 2003 m = hashlib.md5()\r
0e7e7a26 2004 # Add Platform level hash\r
fc8b8dea
SS
2005 HashFile = GlobalData.gPlatformHashFile\r
2006 if path.exists(LongFilePath(HashFile)):\r
2007 FileList.append(HashFile)\r
2008 m.update(HashFile.encode('utf-8'))\r
0e7e7a26 2009 else:\r
fc8b8dea 2010 EdkLogger.quiet("[cache warning]: No Platform HashFile: %s" % HashFile)\r
0e7e7a26
SS
2011\r
2012 # Add Package level hash\r
2013 if self.DependentPackageList:\r
2014 for Pkg in sorted(self.DependentPackageList, key=lambda x: x.PackageName):\r
fc8b8dea
SS
2015 if not (Pkg.PackageName, Pkg.Arch) in GlobalData.gPackageHashFile:\r
2016 EdkLogger.quiet("[cache warning]:No Package %s for module %s[%s]" % (Pkg.PackageName, self.MetaFile.Path, self.Arch))\r
2017 continue\r
2018 HashFile = GlobalData.gPackageHashFile[(Pkg.PackageName, Pkg.Arch)]\r
2019 if path.exists(LongFilePath(HashFile)):\r
2020 FileList.append(HashFile)\r
2021 m.update(HashFile.encode('utf-8'))\r
0e7e7a26 2022 else:\r
fc8b8dea 2023 EdkLogger.quiet("[cache warning]:No Package HashFile: %s" % HashFile)\r
0e7e7a26
SS
2024\r
2025 # Add Module self\r
fc8b8dea
SS
2026 # GenPreMakefileHashList needed in both --binary-destination\r
2027 # and --hash. And --hash might save ModuleHashFile in remote dict\r
2028 # during multiprocessing.\r
2029 if (self.MetaFile.Path, self.Arch) in GlobalData.gModuleHashFile:\r
2030 HashFile = GlobalData.gModuleHashFile[(self.MetaFile.Path, self.Arch)]\r
0e7e7a26 2031 else:\r
fc8b8dea
SS
2032 EdkLogger.quiet("[cache error]:No ModuleHashFile for module: %s[%s]" % (self.MetaFile.Path, self.Arch))\r
2033 if path.exists(LongFilePath(HashFile)):\r
2034 FileList.append(HashFile)\r
2035 m.update(HashFile.encode('utf-8'))\r
0e7e7a26 2036 else:\r
fc8b8dea 2037 EdkLogger.quiet("[cache warning]:No Module HashFile: %s" % HashFile)\r
0e7e7a26 2038\r
fc8b8dea
SS
2039 # Add Library hash\r
2040 if self.LibraryAutoGenList:\r
2041 for Lib in sorted(self.LibraryAutoGenList, key=lambda x: x.MetaFile.Path):\r
0e7e7a26 2042\r
fc8b8dea
SS
2043 if (Lib.MetaFile.Path, Lib.Arch) in GlobalData.gModuleHashFile:\r
2044 HashFile = GlobalData.gModuleHashFile[(Lib.MetaFile.Path, Lib.Arch)]\r
2045 else:\r
2046 EdkLogger.quiet("[cache error]:No ModuleHashFile for lib: %s[%s]" % (Lib.MetaFile.Path, Lib.Arch))\r
2047 if path.exists(LongFilePath(HashFile)):\r
2048 FileList.append(HashFile)\r
2049 m.update(HashFile.encode('utf-8'))\r
2050 else:\r
2051 EdkLogger.quiet("[cache warning]:No Lib HashFile: %s" % HashFile)\r
0e7e7a26 2052\r
fc8b8dea
SS
2053 # Save PreMakeHashFileList\r
2054 FilePath = path.join(self.BuildDir, self.Name + ".PreMakeHashFileList." + m.hexdigest())\r
2055 try:\r
2056 with open(LongFilePath(FilePath), 'w') as f:\r
2057 json.dump(FileList, f, indent=0)\r
2058 except:\r
2059 EdkLogger.quiet("[cache warning]: fail to save PreMake HashFileList: %s" % FilePath)\r
0e7e7a26 2060\r
fc8b8dea
SS
2061 def GenMakefileHashList(self):\r
2062 # GenMakefileHashList only need in --binary-destination which will\r
2063 # everything in local dict. So don't need check remote dict.\r
94459080 2064\r
0e7e7a26
SS
2065 # skip binary module\r
2066 if self.IsBinaryModule:\r
2067 return\r
2068\r
fc8b8dea 2069 FileList = []\r
0e7e7a26 2070 m = hashlib.md5()\r
fc8b8dea
SS
2071 # Add AutoGen hash\r
2072 HashFile = GlobalData.gCMakeHashFile[(self.MetaFile.Path, self.Arch)]\r
2073 if path.exists(LongFilePath(HashFile)):\r
2074 FileList.append(HashFile)\r
2075 m.update(HashFile.encode('utf-8'))\r
2076 else:\r
2077 EdkLogger.quiet("[cache warning]:No AutoGen HashFile: %s" % HashFile)\r
0e7e7a26 2078\r
fc8b8dea
SS
2079 # Add Module self\r
2080 if (self.MetaFile.Path, self.Arch) in GlobalData.gModuleHashFile:\r
2081 HashFile = GlobalData.gModuleHashFile[(self.MetaFile.Path, self.Arch)]\r
2082 else:\r
2083 EdkLogger.quiet("[cache error]:No ModuleHashFile for module: %s[%s]" % (self.MetaFile.Path, self.Arch))\r
2084 if path.exists(LongFilePath(HashFile)):\r
2085 FileList.append(HashFile)\r
2086 m.update(HashFile.encode('utf-8'))\r
2087 else:\r
2088 EdkLogger.quiet("[cache warning]:No Module HashFile: %s" % HashFile)\r
0e7e7a26
SS
2089\r
2090 # Add Library hash\r
2091 if self.LibraryAutoGenList:\r
fc8b8dea
SS
2092 for Lib in sorted(self.LibraryAutoGenList, key=lambda x: x.MetaFile.Path):\r
2093 if (Lib.MetaFile.Path, Lib.Arch) in GlobalData.gModuleHashFile:\r
2094 HashFile = GlobalData.gModuleHashFile[(Lib.MetaFile.Path, Lib.Arch)]\r
2095 else:\r
2096 EdkLogger.quiet("[cache error]:No ModuleHashFile for lib: %s[%s]" % (Lib.MetaFile.Path, Lib.Arch))\r
2097 if path.exists(LongFilePath(HashFile)):\r
2098 FileList.append(HashFile)\r
2099 m.update(HashFile.encode('utf-8'))\r
2100 else:\r
2101 EdkLogger.quiet("[cache warning]:No Lib HashFile: %s" % HashFile)\r
0e7e7a26 2102\r
fc8b8dea
SS
2103 # Save MakeHashFileList\r
2104 FilePath = path.join(self.BuildDir, self.Name + ".MakeHashFileList." + m.hexdigest())\r
2105 try:\r
2106 with open(LongFilePath(FilePath), 'w') as f:\r
2107 json.dump(FileList, f, indent=0)\r
2108 except:\r
2109 EdkLogger.quiet("[cache warning]: fail to save Make HashFileList: %s" % FilePath)\r
2110\r
2111 def CheckHashChainFile(self, HashChainFile):\r
2112 # Assume the HashChainFile basename format is the 'x.hashchain.16BytesHexStr'\r
2113 # The x is module name and the 16BytesHexStr is md5 hexdigest of\r
2114 # all hashchain files content\r
2115 HashStr = HashChainFile.split('.')[-1]\r
2116 if len(HashStr) != 32:\r
2117 EdkLogger.quiet("[cache error]: wrong format HashChainFile:%s" % (File))\r
2118 return False\r
0e7e7a26 2119\r
fc8b8dea
SS
2120 try:\r
2121 with open(LongFilePath(HashChainFile), 'r') as f:\r
2122 HashChainList = json.load(f)\r
2123 except:\r
2124 EdkLogger.quiet("[cache error]: fail to load HashChainFile: %s" % HashChainFile)\r
2125 return False\r
0e7e7a26 2126\r
fc8b8dea
SS
2127 # Print the different file info\r
2128 # print(HashChainFile)\r
2129 for idx, (SrcFile, SrcHash) in enumerate (HashChainList):\r
2130 if SrcFile in GlobalData.gFileHashDict:\r
2131 DestHash = GlobalData.gFileHashDict[SrcFile]\r
2132 else:\r
2133 try:\r
2134 with open(LongFilePath(SrcFile), 'rb') as f:\r
2135 Content = f.read()\r
2136 DestHash = hashlib.md5(Content).hexdigest()\r
2137 GlobalData.gFileHashDict[SrcFile] = DestHash\r
2138 except IOError as X:\r
2139 # cache miss if SrcFile is removed in new version code\r
2140 GlobalData.gFileHashDict[SrcFile] = 0\r
2141 EdkLogger.quiet("[cache insight]: first cache miss file in %s is %s" % (HashChainFile, SrcFile))\r
2142 return False\r
2143 if SrcHash != DestHash:\r
2144 EdkLogger.quiet("[cache insight]: first cache miss file in %s is %s" % (HashChainFile, SrcFile))\r
2145 return False\r
2146\r
2147 return True\r
0e7e7a26
SS
2148\r
2149 ## Decide whether we can skip the left autogen and make process\r
fc8b8dea
SS
2150 def CanSkipbyMakeCache(self):\r
2151 # For --binary-source only\r
2152 # CanSkipbyMakeCache consume below dicts:\r
2153 # gModuleMakeCacheStatus\r
2154 # gHashChainStatus\r
2155 # GenPreMakefileHashList produce gModuleMakeCacheStatus, gModuleHashFile dict.\r
2156 # all these dicts might be produced in multiprocessing, so\r
2157 # need check these remote dict\r
2158\r
0e7e7a26
SS
2159 if not GlobalData.gBinCacheSource:\r
2160 return False\r
2161\r
fc8b8dea
SS
2162 if (self.MetaFile.Path, self.Arch) in GlobalData.gModuleMakeCacheStatus:\r
2163 return GlobalData.gModuleMakeCacheStatus[(self.MetaFile.Path, self.Arch)]\r
94459080 2164\r
fc8b8dea 2165 # If Module is binary, which has special build rule, do not skip by cache.\r
0e7e7a26 2166 if self.IsBinaryModule:\r
fc8b8dea
SS
2167 print("[cache miss]: MakeCache: Skip BinaryModule:", self.MetaFile.Path, self.Arch)\r
2168 GlobalData.gModuleMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False\r
0e7e7a26
SS
2169 return False\r
2170\r
fc8b8dea 2171 # see .inc as binary file, do not skip by hash\r
0e7e7a26
SS
2172 for f_ext in self.SourceFileList:\r
2173 if '.inc' in str(f_ext):\r
fc8b8dea
SS
2174 print("[cache miss]: MakeCache: Skip '.inc' File:", self.MetaFile.Path, self.Arch)\r
2175 GlobalData.gModuleMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False\r
0e7e7a26
SS
2176 return False\r
2177\r
fc8b8dea 2178 ModuleCacheDir = path.join(GlobalData.gBinCacheSource, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, self.Arch, self.SourceDir, self.MetaFile.BaseName)\r
0e7e7a26
SS
2179 FfsDir = path.join(GlobalData.gBinCacheSource, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, TAB_FV_DIRECTORY, "Ffs", self.Guid + self.Name)\r
2180\r
2181 ModuleHashPairList = [] # tuple list: [tuple(PreMakefileHash, MakeHash)]\r
fc8b8dea 2182 ModuleHashPair = path.join(ModuleCacheDir, self.Name + ".ModuleHashPair")\r
0e7e7a26 2183 try:\r
fc8b8dea 2184 with open(LongFilePath(ModuleHashPair), 'r') as f:\r
94459080 2185 ModuleHashPairList = json.load(f)\r
0e7e7a26 2186 except:\r
fc8b8dea
SS
2187 # ModuleHashPair might not exist for new added module\r
2188 GlobalData.gModuleMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False\r
0e7e7a26 2189 EdkLogger.quiet("[cache warning]: fail to load ModuleHashPair file: %s" % ModuleHashPair)\r
fc8b8dea 2190 print("[cache miss]: MakeCache:", self.MetaFile.Path, self.Arch)\r
0e7e7a26
SS
2191 return False\r
2192\r
fc8b8dea 2193 # Check the PreMakeHash in ModuleHashPairList one by one\r
0e7e7a26 2194 for idx, (PreMakefileHash, MakeHash) in enumerate (ModuleHashPairList):\r
fc8b8dea
SS
2195 SourceHashDir = path.join(ModuleCacheDir, MakeHash)\r
2196 SourceFfsHashDir = path.join(FfsDir, MakeHash)\r
2197 PreMakeHashFileList_FilePah = path.join(ModuleCacheDir, self.Name + ".PreMakeHashFileList." + PreMakefileHash)\r
2198 MakeHashFileList_FilePah = path.join(ModuleCacheDir, self.Name + ".MakeHashFileList." + MakeHash)\r
0e7e7a26 2199\r
fc8b8dea
SS
2200 try:\r
2201 with open(LongFilePath(MakeHashFileList_FilePah), 'r') as f:\r
2202 MakeHashFileList = json.load(f)\r
2203 except:\r
2204 EdkLogger.quiet("[cache error]: fail to load MakeHashFileList file: %s" % MakeHashFileList_FilePah)\r
2205 continue\r
0e7e7a26 2206\r
fc8b8dea
SS
2207 HashMiss = False\r
2208 for HashChainFile in MakeHashFileList:\r
2209 HashChainStatus = None\r
2210 if HashChainFile in GlobalData.gHashChainStatus:\r
2211 HashChainStatus = GlobalData.gHashChainStatus[HashChainFile]\r
2212 if HashChainStatus == False:\r
2213 HashMiss = True\r
2214 break\r
2215 elif HashChainStatus == True:\r
2216 continue\r
2217 # Convert to path start with cache source dir\r
2218 RelativePath = os.path.relpath(HashChainFile, self.WorkspaceDir)\r
2219 NewFilePath = os.path.join(GlobalData.gBinCacheSource, RelativePath)\r
2220 if self.CheckHashChainFile(NewFilePath):\r
2221 GlobalData.gHashChainStatus[HashChainFile] = True\r
2222 # Save the module self HashFile for GenPreMakefileHashList later usage\r
2223 if self.Name + ".hashchain." in HashChainFile:\r
2224 GlobalData.gModuleHashFile[(self.MetaFile.Path, self.Arch)] = HashChainFile\r
2225 else:\r
2226 GlobalData.gHashChainStatus[HashChainFile] = False\r
2227 HashMiss = True\r
2228 break\r
0e7e7a26 2229\r
fc8b8dea
SS
2230 if HashMiss:\r
2231 continue\r
0e7e7a26 2232\r
fc8b8dea
SS
2233 # PreMakefile cache hit, restore the module build result\r
2234 for root, dir, files in os.walk(SourceHashDir):\r
0e7e7a26
SS
2235 for f in files:\r
2236 File = path.join(root, f)\r
fc8b8dea
SS
2237 self.CacheCopyFile(self.BuildDir, SourceHashDir, File)\r
2238 if os.path.exists(SourceFfsHashDir):\r
2239 for root, dir, files in os.walk(SourceFfsHashDir):\r
2240 for f in files:\r
2241 File = path.join(root, f)\r
2242 self.CacheCopyFile(self.FfsOutputDir, SourceFfsHashDir, File)\r
2243\r
2244 if self.Name == "PcdPeim" or self.Name == "PcdDxe":\r
2245 CreatePcdDatabaseCode(self, TemplateString(), TemplateString())\r
2246\r
2247 print("[cache hit]: MakeCache:", self.MetaFile.Path, self.Arch)\r
2248 GlobalData.gModuleMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = True\r
2249 return True\r
0e7e7a26 2250\r
fc8b8dea
SS
2251 print("[cache miss]: MakeCache:", self.MetaFile.Path, self.Arch)\r
2252 GlobalData.gModuleMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False\r
2253 return False\r
0e7e7a26 2254\r
fc8b8dea
SS
2255 ## Decide whether we can skip the left autogen and make process\r
2256 def CanSkipbyPreMakeCache(self):\r
2257 # CanSkipbyPreMakeCache consume below dicts:\r
2258 # gModulePreMakeCacheStatus\r
2259 # gHashChainStatus\r
2260 # gModuleHashFile\r
2261 # GenPreMakefileHashList produce gModulePreMakeCacheStatus dict.\r
2262 # all these dicts might be produced in multiprocessing, so\r
2263 # need check these remote dicts\r
2264\r
2265 if not GlobalData.gUseHashCache or GlobalData.gBinCacheDest:\r
0e7e7a26
SS
2266 return False\r
2267\r
fc8b8dea
SS
2268 if (self.MetaFile.Path, self.Arch) in GlobalData.gModulePreMakeCacheStatus:\r
2269 return GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)]\r
94459080 2270\r
fc8b8dea 2271 # If Module is binary, which has special build rule, do not skip by cache.\r
0e7e7a26 2272 if self.IsBinaryModule:\r
fc8b8dea
SS
2273 print("[cache miss]: PreMakeCache: Skip BinaryModule:", self.MetaFile.Path, self.Arch)\r
2274 GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False\r
0e7e7a26
SS
2275 return False\r
2276\r
fc8b8dea 2277 # see .inc as binary file, do not skip by hash\r
0e7e7a26
SS
2278 for f_ext in self.SourceFileList:\r
2279 if '.inc' in str(f_ext):\r
fc8b8dea
SS
2280 print("[cache miss]: PreMakeCache: Skip '.inc' File:", self.MetaFile.Path, self.Arch)\r
2281 GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False\r
0e7e7a26
SS
2282 return False\r
2283\r
fc8b8dea 2284 # For --hash only in the incremental build\r
56c786b0 2285 if not GlobalData.gBinCacheSource:\r
fc8b8dea
SS
2286 Files = [path.join(self.BuildDir, f) for f in os.listdir(self.BuildDir) if path.isfile(path.join(self.BuildDir, f))]\r
2287 PreMakeHashFileList_FilePah = None\r
2288 MakeTimeStamp = 0\r
2289 # Find latest PreMakeHashFileList file in self.BuildDir folder\r
2290 for File in Files:\r
2291 if ".PreMakeHashFileList." in File:\r
2292 FileTimeStamp = os.stat(path.join(self.BuildDir, File))[8]\r
2293 if FileTimeStamp > MakeTimeStamp:\r
2294 MakeTimeStamp = FileTimeStamp\r
2295 PreMakeHashFileList_FilePah = File\r
2296 if not PreMakeHashFileList_FilePah:\r
2297 GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False\r
2298 return False\r
56c786b0 2299\r
fc8b8dea
SS
2300 try:\r
2301 with open(LongFilePath(PreMakeHashFileList_FilePah), 'r') as f:\r
2302 PreMakeHashFileList = json.load(f)\r
2303 except:\r
2304 EdkLogger.quiet("[cache error]: fail to load PreMakeHashFileList file: %s" % PreMakeHashFileList_FilePah)\r
2305 print("[cache miss]: PreMakeCache:", self.MetaFile.Path, self.Arch)\r
2306 GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False\r
2307 return False\r
56c786b0 2308\r
fc8b8dea
SS
2309 HashMiss = False\r
2310 for HashChainFile in PreMakeHashFileList:\r
2311 HashChainStatus = None\r
2312 if HashChainFile in GlobalData.gHashChainStatus:\r
2313 HashChainStatus = GlobalData.gHashChainStatus[HashChainFile]\r
2314 if HashChainStatus == False:\r
2315 HashMiss = True\r
2316 break\r
2317 elif HashChainStatus == True:\r
2318 continue\r
2319 if self.CheckHashChainFile(HashChainFile):\r
2320 GlobalData.gHashChainStatus[HashChainFile] = True\r
2321 # Save the module self HashFile for GenPreMakefileHashList later usage\r
2322 if self.Name + ".hashchain." in HashChainFile:\r
2323 GlobalData.gModuleHashFile[(self.MetaFile.Path, self.Arch)] = HashChainFile\r
2324 else:\r
2325 GlobalData.gHashChainStatus[HashChainFile] = False\r
2326 HashMiss = True\r
2327 break\r
56c786b0 2328\r
fc8b8dea
SS
2329 if HashMiss:\r
2330 print("[cache miss]: PreMakeCache:", self.MetaFile.Path, self.Arch)\r
2331 GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False\r
2332 return False\r
2333 else:\r
2334 print("[cache hit]: PreMakeCache:", self.MetaFile.Path, self.Arch)\r
2335 GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = True\r
2336 return True\r
56c786b0 2337\r
fc8b8dea
SS
2338 ModuleCacheDir = path.join(GlobalData.gBinCacheSource, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, self.Arch, self.SourceDir, self.MetaFile.BaseName)\r
2339 FfsDir = path.join(GlobalData.gBinCacheSource, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, TAB_FV_DIRECTORY, "Ffs", self.Guid + self.Name)\r
56c786b0
SS
2340\r
2341 ModuleHashPairList = [] # tuple list: [tuple(PreMakefileHash, MakeHash)]\r
fc8b8dea 2342 ModuleHashPair = path.join(ModuleCacheDir, self.Name + ".ModuleHashPair")\r
56c786b0 2343 try:\r
fc8b8dea 2344 with open(LongFilePath(ModuleHashPair), 'r') as f:\r
94459080 2345 ModuleHashPairList = json.load(f)\r
56c786b0 2346 except:\r
fc8b8dea
SS
2347 # ModuleHashPair might not exist for new added module\r
2348 GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False\r
2349 EdkLogger.quiet("[cache warning]: fail to load ModuleHashPair file: %s" % ModuleHashPair)\r
2350 print("[cache miss]: PreMakeCache:", self.MetaFile.Path, self.Arch)\r
2351 return False\r
56c786b0 2352\r
fc8b8dea 2353 # Check the PreMakeHash in ModuleHashPairList one by one\r
56c786b0 2354 for idx, (PreMakefileHash, MakeHash) in enumerate (ModuleHashPairList):\r
fc8b8dea
SS
2355 SourceHashDir = path.join(ModuleCacheDir, MakeHash)\r
2356 SourceFfsHashDir = path.join(FfsDir, MakeHash)\r
2357 PreMakeHashFileList_FilePah = path.join(ModuleCacheDir, self.Name + ".PreMakeHashFileList." + PreMakefileHash)\r
2358 MakeHashFileList_FilePah = path.join(ModuleCacheDir, self.Name + ".MakeHashFileList." + MakeHash)\r
56c786b0 2359\r
56c786b0 2360 try:\r
fc8b8dea
SS
2361 with open(LongFilePath(PreMakeHashFileList_FilePah), 'r') as f:\r
2362 PreMakeHashFileList = json.load(f)\r
56c786b0 2363 except:\r
fc8b8dea
SS
2364 EdkLogger.quiet("[cache error]: fail to load PreMakeHashFileList file: %s" % PreMakeHashFileList_FilePah)\r
2365 continue\r
56c786b0 2366\r
fc8b8dea
SS
2367 HashMiss = False\r
2368 for HashChainFile in PreMakeHashFileList:\r
2369 HashChainStatus = None\r
2370 if HashChainFile in GlobalData.gHashChainStatus:\r
2371 HashChainStatus = GlobalData.gHashChainStatus[HashChainFile]\r
2372 if HashChainStatus == False:\r
2373 HashMiss = True\r
2374 break\r
2375 elif HashChainStatus == True:\r
2376 continue\r
2377 # Convert to path start with cache source dir\r
2378 RelativePath = os.path.relpath(HashChainFile, self.WorkspaceDir)\r
2379 NewFilePath = os.path.join(GlobalData.gBinCacheSource, RelativePath)\r
2380 if self.CheckHashChainFile(NewFilePath):\r
2381 GlobalData.gHashChainStatus[HashChainFile] = True\r
2382 else:\r
2383 GlobalData.gHashChainStatus[HashChainFile] = False\r
2384 HashMiss = True\r
2385 break\r
e8449e1d 2386\r
fc8b8dea
SS
2387 if HashMiss:\r
2388 continue\r
e8449e1d 2389\r
fc8b8dea
SS
2390 # PreMakefile cache hit, restore the module build result\r
2391 for root, dir, files in os.walk(SourceHashDir):\r
2392 for f in files:\r
2393 File = path.join(root, f)\r
2394 self.CacheCopyFile(self.BuildDir, SourceHashDir, File)\r
2395 if os.path.exists(SourceFfsHashDir):\r
2396 for root, dir, files in os.walk(SourceFfsHashDir):\r
2397 for f in files:\r
2398 File = path.join(root, f)\r
2399 self.CacheCopyFile(self.FfsOutputDir, SourceFfsHashDir, File)\r
2400\r
2401 if self.Name == "PcdPeim" or self.Name == "PcdDxe":\r
2402 CreatePcdDatabaseCode(self, TemplateString(), TemplateString())\r
2403\r
2404 print("[cache hit]: PreMakeCache:", self.MetaFile.Path, self.Arch)\r
2405 GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = True\r
2406 return True\r
e8449e1d 2407\r
fc8b8dea
SS
2408 print("[cache miss]: PreMakeCache:", self.MetaFile.Path, self.Arch)\r
2409 GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False\r
2410 return False\r
e8449e1d 2411\r
fc8b8dea
SS
2412 ## Decide whether we can skip the Module build\r
2413 def CanSkipbyCache(self, gHitSet):\r
2414 # Hashing feature is off\r
2415 if not GlobalData.gBinCacheSource:\r
0e7e7a26
SS
2416 return False\r
2417\r
fc8b8dea 2418 if self in gHitSet:\r
0e7e7a26 2419 return True\r
e8449e1d 2420\r
0e7e7a26 2421 return False\r
e8449e1d
FB
2422\r
2423 ## Decide whether we can skip the ModuleAutoGen process\r
2424 # If any source file is newer than the module than we cannot skip\r
2425 #\r
2426 def CanSkip(self):\r
0e7e7a26
SS
2427 # Don't skip if cache feature enabled\r
2428 if GlobalData.gUseHashCache or GlobalData.gBinCacheDest or GlobalData.gBinCacheSource:\r
2429 return False\r
e8449e1d
FB
2430 if self.MakeFileDir in GlobalData.gSikpAutoGenCache:\r
2431 return True\r
2432 if not os.path.exists(self.TimeStampPath):\r
2433 return False\r
2434 #last creation time of the module\r
2435 DstTimeStamp = os.stat(self.TimeStampPath)[8]\r
2436\r
2437 SrcTimeStamp = self.Workspace._SrcTimeStamp\r
2438 if SrcTimeStamp > DstTimeStamp:\r
2439 return False\r
2440\r
2441 with open(self.TimeStampPath,'r') as f:\r
2442 for source in f:\r
2443 source = source.rstrip('\n')\r
2444 if not os.path.exists(source):\r
2445 return False\r
2446 if source not in ModuleAutoGen.TimeDict :\r
2447 ModuleAutoGen.TimeDict[source] = os.stat(source)[8]\r
2448 if ModuleAutoGen.TimeDict[source] > DstTimeStamp:\r
2449 return False\r
2450 GlobalData.gSikpAutoGenCache.add(self.MakeFileDir)\r
2451 return True\r
2452\r
2453 @cached_property\r
2454 def TimeStampPath(self):\r
2455 return os.path.join(self.MakeFileDir, 'AutoGenTimeStamp')\r