2 # Create makefile for MS nmake and GNU make
4 # Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
5 # SPDX-License-Identifier: BSD-2-Clause-Patent
7 from __future__
import absolute_import
8 from AutoGen
.AutoGen
import AutoGen
9 from Common
.LongFilePathSupport
import LongFilePath
, CopyLongFilePath
10 from Common
.BuildToolError
import *
11 from Common
.DataType
import *
12 from Common
.Misc
import *
13 from Common
.StringUtils
import NormPath
,GetSplitList
14 from collections
import defaultdict
15 from Workspace
.WorkspaceCommon
import OrderedListDict
16 import os
.path
as path
19 from . import InfSectionParser
22 from . import GenDepex
23 from io
import BytesIO
24 from GenPatchPcdTable
.GenPatchPcdTable
import parsePcdInfoFromMapFile
25 from Workspace
.MetaFileCommentParser
import UsageList
26 from .GenPcdDb
import CreatePcdDatabaseCode
27 from Common
.caching
import cached_class_function
28 from AutoGen
.ModuleAutoGenHelper
import PlatformInfo
,WorkSpaceInfo
32 ## Mapping Makefile type
33 gMakeTypeMap
= {TAB_COMPILER_MSFT
:"nmake", "GCC":"gmake"}
35 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT
36 # is the former use /I , the Latter used -I to specify include directories
38 gBuildOptIncludePatternMsft
= re
.compile(r
"(?:.*?)/I[ \t]*([^ ]*)", re
.MULTILINE | re
.DOTALL
)
39 gBuildOptIncludePatternOther
= re
.compile(r
"(?:.*?)-I[ \t]*([^ ]*)", re
.MULTILINE | re
.DOTALL
)
41 ## default file name for AutoGen
42 gAutoGenCodeFileName
= "AutoGen.c"
43 gAutoGenHeaderFileName
= "AutoGen.h"
44 gAutoGenStringFileName
= "%(module_name)sStrDefs.h"
45 gAutoGenStringFormFileName
= "%(module_name)sStrDefs.hpk"
46 gAutoGenDepexFileName
= "%(module_name)s.depex"
47 gAutoGenImageDefFileName
= "%(module_name)sImgDefs.h"
48 gAutoGenIdfFileName
= "%(module_name)sIdf.hpk"
49 gInfSpecVersion
= "0x00010017"
52 # Match name = variable
54 gEfiVarStoreNamePattern
= re
.compile("\s*name\s*=\s*(\w+)")
56 # The format of guid in efivarstore statement likes following and must be correct:
57 # guid = {0xA04A27f4, 0xDF00, 0x4D42, {0xB5, 0x52, 0x39, 0x51, 0x13, 0x02, 0x11, 0x3D}}
59 gEfiVarStoreGuidPattern
= re
.compile("\s*guid\s*=\s*({.*?{.*?}\s*})")
62 # Template string to generic AsBuilt INF
64 gAsBuiltInfHeaderString
= TemplateString("""${header_comments}
70 INF_VERSION = ${module_inf_version}
71 BASE_NAME = ${module_name}
72 FILE_GUID = ${module_guid}
73 MODULE_TYPE = ${module_module_type}${BEGIN}
74 VERSION_STRING = ${module_version_string}${END}${BEGIN}
75 PCD_IS_DRIVER = ${pcd_is_driver_string}${END}${BEGIN}
76 UEFI_SPECIFICATION_VERSION = ${module_uefi_specification_version}${END}${BEGIN}
77 PI_SPECIFICATION_VERSION = ${module_pi_specification_version}${END}${BEGIN}
78 ENTRY_POINT = ${module_entry_point}${END}${BEGIN}
79 UNLOAD_IMAGE = ${module_unload_image}${END}${BEGIN}
80 CONSTRUCTOR = ${module_constructor}${END}${BEGIN}
81 DESTRUCTOR = ${module_destructor}${END}${BEGIN}
82 SHADOW = ${module_shadow}${END}${BEGIN}
83 PCI_VENDOR_ID = ${module_pci_vendor_id}${END}${BEGIN}
84 PCI_DEVICE_ID = ${module_pci_device_id}${END}${BEGIN}
85 PCI_CLASS_CODE = ${module_pci_class_code}${END}${BEGIN}
86 PCI_REVISION = ${module_pci_revision}${END}${BEGIN}
87 BUILD_NUMBER = ${module_build_number}${END}${BEGIN}
88 SPEC = ${module_spec}${END}${BEGIN}
89 UEFI_HII_RESOURCE_SECTION = ${module_uefi_hii_resource_section}${END}${BEGIN}
90 MODULE_UNI_FILE = ${module_uni_file}${END}
92 [Packages.${module_arch}]${BEGIN}
95 [Binaries.${module_arch}]${BEGIN}
98 [PatchPcd.${module_arch}]${BEGIN}
102 [Protocols.${module_arch}]${BEGIN}
106 [Ppis.${module_arch}]${BEGIN}
110 [Guids.${module_arch}]${BEGIN}
114 [PcdEx.${module_arch}]${BEGIN}
118 [LibraryClasses.${module_arch}]
119 ## @LIB_INSTANCES${BEGIN}
120 # ${libraryclasses_item}${END}
124 ${userextension_tianocore_item}
128 [BuildOptions.${module_arch}]
130 ## ${flags_item}${END}
133 # extend lists contained in a dictionary with lists stored in another dictionary
134 # if CopyToDict is not derived from DefaultDict(list) then this may raise exception
136 def ExtendCopyDictionaryLists(CopyToDict
, CopyFromDict
):
137 for Key
in CopyFromDict
:
138 CopyToDict
[Key
].extend(CopyFromDict
[Key
])
140 # Create a directory specified by a set of path elements and return the full path
141 def _MakeDir(PathList
):
142 RetVal
= path
.join(*PathList
)
143 CreateDirectory(RetVal
)
147 # Convert string to C format array
149 def _ConvertStringToByteArray(Value
):
150 Value
= Value
.strip()
154 if not Value
.endswith('}'):
156 Value
= Value
.replace(' ', '').replace('{', '').replace('}', '')
157 ValFields
= Value
.split(',')
159 for Index
in range(len(ValFields
)):
160 ValFields
[Index
] = str(int(ValFields
[Index
], 0))
163 Value
= '{' + ','.join(ValFields
) + '}'
167 if Value
.startswith('L"'):
168 if not Value
.endswith('"'):
172 elif not Value
.startswith('"') or not Value
.endswith('"'):
175 Value
= eval(Value
) # translate escape character
177 for Index
in range(0, len(Value
)):
179 NewValue
= NewValue
+ str(ord(Value
[Index
]) % 0x10000) + ','
181 NewValue
= NewValue
+ str(ord(Value
[Index
]) % 0x100) + ','
182 Value
= NewValue
+ '0}'
185 ## ModuleAutoGen class
187 # This class encapsules the AutoGen behaviors for the build tools. In addition to
188 # the generation of AutoGen.h and AutoGen.c, it will generate *.depex file according
189 # to the [depex] section in module's inf file.
191 class ModuleAutoGen(AutoGen
):
192 # call super().__init__ then call the worker function with different parameter count
193 def __init__(self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
194 if not hasattr(self
, "_Init"):
195 self
._InitWorker
(Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
)
198 ## Cache the timestamps of metafiles of every module in a class attribute
202 def __new__(cls
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
203 # check if this module is employed by active platform
204 if not PlatformInfo(Workspace
, args
[0], Target
, Toolchain
, Arch
,args
[-1]).ValidModule(MetaFile
):
205 EdkLogger
.verbose("Module [%s] for [%s] is not employed by active platform\n" \
208 return super(ModuleAutoGen
, cls
).__new
__(cls
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
)
210 ## Initialize ModuleAutoGen
212 # @param Workspace EdkIIWorkspaceBuild object
213 # @param ModuleFile The path of module file
214 # @param Target Build target (DEBUG, RELEASE)
215 # @param Toolchain Name of tool chain
216 # @param Arch The arch the module supports
217 # @param PlatformFile Platform meta-file
219 def _InitWorker(self
, Workspace
, ModuleFile
, Target
, Toolchain
, Arch
, PlatformFile
,DataPipe
):
220 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "AutoGen module [%s] [%s]" % (ModuleFile
, Arch
))
221 GlobalData
.gProcessingFile
= "%s [%s, %s, %s]" % (ModuleFile
, Arch
, Toolchain
, Target
)
223 self
.Workspace
= Workspace
224 self
.WorkspaceDir
= ""
225 self
.PlatformInfo
= None
226 self
.DataPipe
= DataPipe
227 self
.__init
_platform
_info
__()
228 self
.MetaFile
= ModuleFile
229 self
.SourceDir
= self
.MetaFile
.SubDir
230 self
.SourceDir
= mws
.relpath(self
.SourceDir
, self
.WorkspaceDir
)
232 self
.ToolChain
= Toolchain
233 self
.BuildTarget
= Target
235 self
.ToolChainFamily
= self
.PlatformInfo
.ToolChainFamily
236 self
.BuildRuleFamily
= self
.PlatformInfo
.BuildRuleFamily
238 self
.IsCodeFileCreated
= False
239 self
.IsAsBuiltInfCreated
= False
240 self
.DepexGenerated
= False
242 self
.BuildDatabase
= self
.Workspace
.BuildDatabase
243 self
.BuildRuleOrder
= None
246 self
._GuidComments
= OrderedListDict()
247 self
._ProtocolComments
= OrderedListDict()
248 self
._PpiComments
= OrderedListDict()
249 self
._BuildTargets
= None
250 self
._IntroBuildTargetList
= None
251 self
._FinalBuildTargetList
= None
252 self
._FileTypes
= None
254 self
.AutoGenDepSet
= set()
255 self
.ReferenceModules
= []
258 self
.FileDependCache
= {}
260 def __init_platform_info__(self
):
261 pinfo
= self
.DataPipe
.Get("P_Info")
262 self
.WorkspaceDir
= pinfo
.get("WorkspaceDir")
263 self
.PlatformInfo
= PlatformInfo(self
.Workspace
,pinfo
.get("ActivePlatform"),pinfo
.get("Target"),pinfo
.get("ToolChain"),pinfo
.get("Arch"),self
.DataPipe
)
264 ## hash() operator of ModuleAutoGen
266 # The module file path and arch string will be used to represent
267 # hash value of this object
269 # @retval int Hash value of the module file path and arch
271 @cached_class_function
273 return hash((self
.MetaFile
, self
.Arch
, self
.ToolChain
,self
.BuildTarget
))
275 return "%s [%s]" % (self
.MetaFile
, self
.Arch
)
277 # Get FixedAtBuild Pcds of this Module
279 def FixedAtBuildPcds(self
):
281 for Pcd
in self
.ModulePcdList
:
282 if Pcd
.Type
!= TAB_PCDS_FIXED_AT_BUILD
:
284 if Pcd
not in RetVal
:
289 def FixedVoidTypePcds(self
):
291 for Pcd
in self
.FixedAtBuildPcds
:
292 if Pcd
.DatumType
== TAB_VOID
:
293 if '.'.join((Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
)) not in RetVal
:
294 RetVal
['.'.join((Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
))] = Pcd
.DefaultValue
298 def UniqueBaseName(self
):
299 ModuleNames
= self
.DataPipe
.Get("M_Name")
302 return ModuleNames
.get((self
.Name
,self
.MetaFile
),self
.Name
)
304 # Macros could be used in build_rule.txt (also Makefile)
308 ("WORKSPACE" ,self
.WorkspaceDir
),
309 ("MODULE_NAME" ,self
.Name
),
310 ("MODULE_NAME_GUID" ,self
.UniqueBaseName
),
311 ("MODULE_GUID" ,self
.Guid
),
312 ("MODULE_VERSION" ,self
.Version
),
313 ("MODULE_TYPE" ,self
.ModuleType
),
314 ("MODULE_FILE" ,str(self
.MetaFile
)),
315 ("MODULE_FILE_BASE_NAME" ,self
.MetaFile
.BaseName
),
316 ("MODULE_RELATIVE_DIR" ,self
.SourceDir
),
317 ("MODULE_DIR" ,self
.SourceDir
),
318 ("BASE_NAME" ,self
.Name
),
320 ("TOOLCHAIN" ,self
.ToolChain
),
321 ("TOOLCHAIN_TAG" ,self
.ToolChain
),
322 ("TOOL_CHAIN_TAG" ,self
.ToolChain
),
323 ("TARGET" ,self
.BuildTarget
),
324 ("BUILD_DIR" ,self
.PlatformInfo
.BuildDir
),
325 ("BIN_DIR" ,os
.path
.join(self
.PlatformInfo
.BuildDir
, self
.Arch
)),
326 ("LIB_DIR" ,os
.path
.join(self
.PlatformInfo
.BuildDir
, self
.Arch
)),
327 ("MODULE_BUILD_DIR" ,self
.BuildDir
),
328 ("OUTPUT_DIR" ,self
.OutputDir
),
329 ("DEBUG_DIR" ,self
.DebugDir
),
330 ("DEST_DIR_OUTPUT" ,self
.OutputDir
),
331 ("DEST_DIR_DEBUG" ,self
.DebugDir
),
332 ("PLATFORM_NAME" ,self
.PlatformInfo
.Name
),
333 ("PLATFORM_GUID" ,self
.PlatformInfo
.Guid
),
334 ("PLATFORM_VERSION" ,self
.PlatformInfo
.Version
),
335 ("PLATFORM_RELATIVE_DIR" ,self
.PlatformInfo
.SourceDir
),
336 ("PLATFORM_DIR" ,mws
.join(self
.WorkspaceDir
, self
.PlatformInfo
.SourceDir
)),
337 ("PLATFORM_OUTPUT_DIR" ,self
.PlatformInfo
.OutputDir
),
338 ("FFS_OUTPUT_DIR" ,self
.FfsOutputDir
)
341 ## Return the module build data object
344 return self
.BuildDatabase
[self
.MetaFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
346 ## Return the module name
349 return self
.Module
.BaseName
351 ## Return the module DxsFile if exist
354 return self
.Module
.DxsFile
356 ## Return the module meta-file GUID
360 # To build same module more than once, the module path with FILE_GUID overridden has
361 # the file name FILE_GUIDmodule.inf, but the relative path (self.MetaFile.File) is the real path
362 # in DSC. The overridden GUID can be retrieved from file name
364 if os
.path
.basename(self
.MetaFile
.File
) != os
.path
.basename(self
.MetaFile
.Path
):
366 # Length of GUID is 36
368 return os
.path
.basename(self
.MetaFile
.Path
)[:36]
369 return self
.Module
.Guid
371 ## Return the module version
374 return self
.Module
.Version
376 ## Return the module type
378 def ModuleType(self
):
379 return self
.Module
.ModuleType
381 ## Return the component type (for Edk.x style of module)
383 def ComponentType(self
):
384 return self
.Module
.ComponentType
386 ## Return the build type
389 return self
.Module
.BuildType
391 ## Return the PCD_IS_DRIVER setting
393 def PcdIsDriver(self
):
394 return self
.Module
.PcdIsDriver
396 ## Return the autogen version, i.e. module meta-file version
398 def AutoGenVersion(self
):
399 return self
.Module
.AutoGenVersion
401 ## Check if the module is library or not
404 return bool(self
.Module
.LibraryClass
)
406 ## Check if the module is binary module or not
408 def IsBinaryModule(self
):
409 return self
.Module
.IsBinaryModule
411 ## Return the directory to store intermediate files of the module
415 self
.PlatformInfo
.BuildDir
,
418 self
.MetaFile
.BaseName
421 ## Return the directory to store the intermediate object files of the module
424 return _MakeDir((self
.BuildDir
, "OUTPUT"))
426 ## Return the directory path to store ffs file
428 def FfsOutputDir(self
):
429 if GlobalData
.gFdfParser
:
430 return path
.join(self
.PlatformInfo
.BuildDir
, TAB_FV_DIRECTORY
, "Ffs", self
.Guid
+ self
.Name
)
433 ## Return the directory to store auto-gened source files of the module
436 return _MakeDir((self
.BuildDir
, "DEBUG"))
438 ## Return the path of custom file
440 def CustomMakefile(self
):
442 for Type
in self
.Module
.CustomMakefile
:
443 MakeType
= gMakeTypeMap
[Type
] if Type
in gMakeTypeMap
else 'nmake'
444 File
= os
.path
.join(self
.SourceDir
, self
.Module
.CustomMakefile
[Type
])
445 RetVal
[MakeType
] = File
448 ## Return the directory of the makefile
450 # @retval string The directory string of module's makefile
453 def MakeFileDir(self
):
456 ## Return build command string
458 # @retval string Build command string
461 def BuildCommand(self
):
462 return self
.PlatformInfo
.BuildCommand
464 ## Get Module package and Platform package
466 # @retval list The list of package object
469 def PackageList(self
):
471 if self
.Module
.Packages
:
472 PkagList
.extend(self
.Module
.Packages
)
473 Platform
= self
.BuildDatabase
[self
.PlatformInfo
.MetaFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
474 for Package
in Platform
.Packages
:
475 if Package
in PkagList
:
477 PkagList
.append(Package
)
480 ## Get object list of all packages the module and its dependent libraries belong to and the Platform depends on
482 # @retval list The list of package object
485 def DerivedPackageList(self
):
487 PackageList
.extend(self
.PackageList
)
488 for M
in self
.DependentLibraryList
:
489 for Package
in M
.Packages
:
490 if Package
in PackageList
:
492 PackageList
.append(Package
)
495 ## Get the depex string
497 # @return : a string contain all depex expression.
498 def _GetDepexExpresionString(self
):
501 ## DPX_SOURCE IN Define section.
502 if self
.Module
.DxsFile
:
504 for M
in [self
.Module
] + self
.DependentLibraryList
:
505 Filename
= M
.MetaFile
.Path
506 InfObj
= InfSectionParser
.InfSectionParser(Filename
)
507 DepexExpressionList
= InfObj
.GetDepexExpresionList()
508 for DepexExpression
in DepexExpressionList
:
509 for key
in DepexExpression
:
510 Arch
, ModuleType
= key
511 DepexExpr
= [x
for x
in DepexExpression
[key
] if not str(x
).startswith('#')]
512 # the type of build module is USER_DEFINED.
513 # All different DEPEX section tags would be copied into the As Built INF file
514 # and there would be separate DEPEX section tags
515 if self
.ModuleType
.upper() == SUP_MODULE_USER_DEFINED
or self
.ModuleType
.upper() == SUP_MODULE_HOST_APPLICATION
:
516 if (Arch
.upper() == self
.Arch
.upper()) and (ModuleType
.upper() != TAB_ARCH_COMMON
):
517 DepexList
.append({(Arch
, ModuleType
): DepexExpr
})
519 if Arch
.upper() == TAB_ARCH_COMMON
or \
520 (Arch
.upper() == self
.Arch
.upper() and \
521 ModuleType
.upper() in [TAB_ARCH_COMMON
, self
.ModuleType
.upper()]):
522 DepexList
.append({(Arch
, ModuleType
): DepexExpr
})
524 #the type of build module is USER_DEFINED.
525 if self
.ModuleType
.upper() == SUP_MODULE_USER_DEFINED
or self
.ModuleType
.upper() == SUP_MODULE_HOST_APPLICATION
:
526 for Depex
in DepexList
:
528 DepexStr
+= '[Depex.%s.%s]\n' % key
529 DepexStr
+= '\n'.join('# '+ val
for val
in Depex
[key
])
532 return '[Depex.%s]\n' % self
.Arch
535 #the type of build module not is USER_DEFINED.
537 for Depex
in DepexList
:
542 for D
in Depex
.values():
543 DepexStr
+= ' '.join(val
for val
in D
)
544 Index
= DepexStr
.find('END')
545 if Index
> -1 and Index
== len(DepexStr
) - 3:
546 DepexStr
= DepexStr
[:-3]
547 DepexStr
= DepexStr
.strip()
550 DepexStr
= DepexStr
.lstrip('(').rstrip(')').strip()
552 return '[Depex.%s]\n' % self
.Arch
553 return '[Depex.%s]\n# ' % self
.Arch
+ DepexStr
555 ## Merge dependency expression
557 # @retval list The token list of the dependency expression after parsed
561 if self
.DxsFile
or self
.IsLibrary
or TAB_DEPENDENCY_EXPRESSION_FILE
in self
.FileTypes
:
566 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expression
568 FixedVoidTypePcds
= {}
569 for M
in [self
] + self
.LibraryAutoGenList
:
570 FixedVoidTypePcds
.update(M
.FixedVoidTypePcds
)
571 for M
in [self
] + self
.LibraryAutoGenList
:
573 for D
in M
.Module
.Depex
[self
.Arch
, self
.ModuleType
]:
575 DepexList
.append('AND')
576 DepexList
.append('(')
577 #replace D with value if D is FixedAtBuild PCD
584 Value
= FixedVoidTypePcds
[item
]
585 if len(Value
.split(',')) != 16:
586 EdkLogger
.error("build", FORMAT_INVALID
,
587 "{} used in [Depex] section should be used as FixedAtBuild type and VOID* datum type and 16 bytes in the module.".format(item
))
588 NewList
.append(Value
)
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
))
592 DepexList
.extend(NewList
)
593 if DepexList
[-1] == 'END': # no need of a END at this time
595 DepexList
.append(')')
598 EdkLogger
.verbose("DEPEX[%s] (+%s) = %s" % (self
.Name
, M
.Module
.BaseName
, DepexList
))
599 if 'BEFORE' in DepexList
or 'AFTER' in DepexList
:
601 if len(DepexList
) > 0:
602 EdkLogger
.verbose('')
603 return {self
.ModuleType
:DepexList
}
605 ## Merge dependency expression
607 # @retval list The token list of the dependency expression after parsed
610 def DepexExpressionDict(self
):
611 if self
.DxsFile
or self
.IsLibrary
or TAB_DEPENDENCY_EXPRESSION_FILE
in self
.FileTypes
:
614 DepexExpressionString
= ''
616 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion
618 for M
in [self
.Module
] + self
.DependentLibraryList
:
620 for D
in M
.DepexExpression
[self
.Arch
, self
.ModuleType
]:
621 if DepexExpressionString
!= '':
622 DepexExpressionString
+= ' AND '
623 DepexExpressionString
+= '('
624 DepexExpressionString
+= D
625 DepexExpressionString
= DepexExpressionString
.rstrip('END').strip()
626 DepexExpressionString
+= ')'
629 EdkLogger
.verbose("DEPEX[%s] (+%s) = %s" % (self
.Name
, M
.BaseName
, DepexExpressionString
))
630 if 'BEFORE' in DepexExpressionString
or 'AFTER' in DepexExpressionString
:
632 if len(DepexExpressionString
) > 0:
633 EdkLogger
.verbose('')
635 return {self
.ModuleType
:DepexExpressionString
}
637 # Get the tiano core user extension, it is contain dependent library.
638 # @retval: a list contain tiano core userextension.
640 def _GetTianoCoreUserExtensionList(self
):
641 TianoCoreUserExtentionList
= []
642 for M
in [self
.Module
] + self
.DependentLibraryList
:
643 Filename
= M
.MetaFile
.Path
644 InfObj
= InfSectionParser
.InfSectionParser(Filename
)
645 TianoCoreUserExtenList
= InfObj
.GetUserExtensionTianoCore()
646 for TianoCoreUserExtent
in TianoCoreUserExtenList
:
647 for Section
in TianoCoreUserExtent
:
648 ItemList
= Section
.split(TAB_SPLIT
)
650 if len(ItemList
) == 4:
652 if Arch
.upper() == TAB_ARCH_COMMON
or Arch
.upper() == self
.Arch
.upper():
654 TianoCoreList
.extend([TAB_SECTION_START
+ Section
+ TAB_SECTION_END
])
655 TianoCoreList
.extend(TianoCoreUserExtent
[Section
][:])
656 TianoCoreList
.append('\n')
657 TianoCoreUserExtentionList
.append(TianoCoreList
)
659 return TianoCoreUserExtentionList
661 ## Return the list of specification version required for the module
663 # @retval list The list of specification defined in module file
666 def Specification(self
):
667 return self
.Module
.Specification
669 ## Tool option for the module build
671 # @param PlatformInfo The object of PlatformBuildInfo
672 # @retval dict The dict containing valid options
675 def BuildOption(self
):
676 RetVal
, self
.BuildRuleOrder
= self
.PlatformInfo
.ApplyBuildOption(self
.Module
)
677 if self
.BuildRuleOrder
:
678 self
.BuildRuleOrder
= ['.%s' % Ext
for Ext
in self
.BuildRuleOrder
.split()]
681 ## Get include path list from tool option for the module build
683 # @retval list The include path list
686 def BuildOptionIncPathList(self
):
688 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT
689 # is the former use /I , the Latter used -I to specify include directories
691 if self
.PlatformInfo
.ToolChainFamily
in (TAB_COMPILER_MSFT
):
692 BuildOptIncludeRegEx
= gBuildOptIncludePatternMsft
693 elif self
.PlatformInfo
.ToolChainFamily
in ('INTEL', 'GCC', 'RVCT'):
694 BuildOptIncludeRegEx
= gBuildOptIncludePatternOther
697 # New ToolChainFamily, don't known whether there is option to specify include directories
702 for Tool
in ('CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'ASM'):
704 FlagOption
= self
.BuildOption
[Tool
]['FLAGS']
708 if self
.ToolChainFamily
!= 'RVCT':
709 IncPathList
= [NormPath(Path
, self
.Macros
) for Path
in BuildOptIncludeRegEx
.findall(FlagOption
)]
712 # RVCT may specify a list of directory seperated by commas
715 for Path
in BuildOptIncludeRegEx
.findall(FlagOption
):
716 PathList
= GetSplitList(Path
, TAB_COMMA_SPLIT
)
717 IncPathList
.extend(NormPath(PathEntry
, self
.Macros
) for PathEntry
in PathList
)
720 # EDK II modules must not reference header files outside of the packages they depend on or
721 # within the module's directory tree. Report error if violation.
723 if GlobalData
.gDisableIncludePathCheck
== False:
724 for Path
in IncPathList
:
725 if (Path
not in self
.IncludePathList
) and (CommonPath([Path
, self
.MetaFile
.Dir
]) != self
.MetaFile
.Dir
):
726 ErrMsg
= "The include directory for the EDK II module in this line is invalid %s specified in %s FLAGS '%s'" % (Path
, Tool
, FlagOption
)
727 EdkLogger
.error("build",
730 File
=str(self
.MetaFile
))
731 RetVal
+= IncPathList
734 ## Return a list of files which can be built from source
736 # What kind of files can be built is determined by build rules in
737 # $(CONF_DIRECTORY)/build_rule.txt and toolchain family.
740 def SourceFileList(self
):
742 ToolChainTagSet
= {"", TAB_STAR
, self
.ToolChain
}
743 ToolChainFamilySet
= {"", TAB_STAR
, self
.ToolChainFamily
, self
.BuildRuleFamily
}
744 for F
in self
.Module
.Sources
:
746 if F
.TagName
not in ToolChainTagSet
:
747 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "The toolchain [%s] for processing file [%s] is found, "
748 "but [%s] is currently used" % (F
.TagName
, str(F
), self
.ToolChain
))
750 # match tool chain family or build rule family
751 if F
.ToolChainFamily
not in ToolChainFamilySet
:
754 "The file [%s] must be built by tools of [%s], " \
755 "but current toolchain family is [%s], buildrule family is [%s]" \
756 % (str(F
), F
.ToolChainFamily
, self
.ToolChainFamily
, self
.BuildRuleFamily
))
759 # add the file path into search path list for file including
760 if F
.Dir
not in self
.IncludePathList
:
761 self
.IncludePathList
.insert(0, F
.Dir
)
764 self
._MatchBuildRuleOrder
(RetVal
)
767 self
._ApplyBuildRule
(F
, TAB_UNKNOWN_FILE
)
770 def _MatchBuildRuleOrder(self
, FileList
):
773 for SingleFile
in FileList
:
774 if self
.BuildRuleOrder
and SingleFile
.Ext
in self
.BuildRuleOrder
and SingleFile
.Ext
in self
.BuildRules
:
775 key
= SingleFile
.Path
.rsplit(SingleFile
.Ext
,1)[0]
776 if key
in Order_Dict
:
777 Order_Dict
[key
].append(SingleFile
.Ext
)
779 Order_Dict
[key
] = [SingleFile
.Ext
]
783 if len(Order_Dict
[F
]) > 1:
784 Order_Dict
[F
].sort(key
=lambda i
: self
.BuildRuleOrder
.index(i
))
785 for Ext
in Order_Dict
[F
][1:]:
786 RemoveList
.append(F
+ Ext
)
788 for item
in RemoveList
:
789 FileList
.remove(item
)
793 ## Return the list of unicode files
795 def UnicodeFileList(self
):
796 return self
.FileTypes
.get(TAB_UNICODE_FILE
,[])
798 ## Return the list of vfr files
800 def VfrFileList(self
):
801 return self
.FileTypes
.get(TAB_VFR_FILE
, [])
803 ## Return the list of Image Definition files
805 def IdfFileList(self
):
806 return self
.FileTypes
.get(TAB_IMAGE_FILE
,[])
808 ## Return a list of files which can be built from binary
810 # "Build" binary files are just to copy them to build directory.
812 # @retval list The list of files which can be built later
815 def BinaryFileList(self
):
817 for F
in self
.Module
.Binaries
:
818 if F
.Target
not in [TAB_ARCH_COMMON
, TAB_STAR
] and F
.Target
!= self
.BuildTarget
:
821 self
._ApplyBuildRule
(F
, F
.Type
, BinaryFileList
=RetVal
)
825 def BuildRules(self
):
827 BuildRuleDatabase
= self
.PlatformInfo
.BuildRule
828 for Type
in BuildRuleDatabase
.FileTypeList
:
829 #first try getting build rule by BuildRuleFamily
830 RuleObject
= BuildRuleDatabase
[Type
, self
.BuildType
, self
.Arch
, self
.BuildRuleFamily
]
832 # build type is always module type, but ...
833 if self
.ModuleType
!= self
.BuildType
:
834 RuleObject
= BuildRuleDatabase
[Type
, self
.ModuleType
, self
.Arch
, self
.BuildRuleFamily
]
835 #second try getting build rule by ToolChainFamily
837 RuleObject
= BuildRuleDatabase
[Type
, self
.BuildType
, self
.Arch
, self
.ToolChainFamily
]
839 # build type is always module type, but ...
840 if self
.ModuleType
!= self
.BuildType
:
841 RuleObject
= BuildRuleDatabase
[Type
, self
.ModuleType
, self
.Arch
, self
.ToolChainFamily
]
844 RuleObject
= RuleObject
.Instantiate(self
.Macros
)
845 RetVal
[Type
] = RuleObject
846 for Ext
in RuleObject
.SourceFileExtList
:
847 RetVal
[Ext
] = RuleObject
850 def _ApplyBuildRule(self
, File
, FileType
, BinaryFileList
=None):
851 if self
._BuildTargets
is None:
852 self
._IntroBuildTargetList
= set()
853 self
._FinalBuildTargetList
= set()
854 self
._BuildTargets
= defaultdict(set)
855 self
._FileTypes
= defaultdict(set)
857 if not BinaryFileList
:
858 BinaryFileList
= self
.BinaryFileList
860 SubDirectory
= os
.path
.join(self
.OutputDir
, File
.SubDir
)
861 if not os
.path
.exists(SubDirectory
):
862 CreateDirectory(SubDirectory
)
864 FinalTargetName
= set()
869 # Make sure to get build rule order value
873 while Index
< len(SourceList
):
874 # Reset the FileType if not the first iteration.
876 FileType
= TAB_UNKNOWN_FILE
877 Source
= SourceList
[Index
]
881 CreateDirectory(Source
.Dir
)
883 if File
.IsBinary
and File
== Source
and File
in BinaryFileList
:
884 # Skip all files that are not binary libraries
885 if not self
.IsLibrary
:
887 RuleObject
= self
.BuildRules
[TAB_DEFAULT_BINARY_FILE
]
888 elif FileType
in self
.BuildRules
:
889 RuleObject
= self
.BuildRules
[FileType
]
890 elif Source
.Ext
in self
.BuildRules
:
891 RuleObject
= self
.BuildRules
[Source
.Ext
]
893 # No more rule to apply: Source is a final target.
894 FinalTargetName
.add(Source
)
897 FileType
= RuleObject
.SourceFileType
898 self
._FileTypes
[FileType
].add(Source
)
900 # stop at STATIC_LIBRARY for library
901 if self
.IsLibrary
and FileType
== TAB_STATIC_LIBRARY
:
902 FinalTargetName
.add(Source
)
905 Target
= RuleObject
.Apply(Source
, self
.BuildRuleOrder
)
907 # No Target: Source is a final target.
908 FinalTargetName
.add(Source
)
911 TargetList
.add(Target
)
912 self
._BuildTargets
[FileType
].add(Target
)
914 if not Source
.IsBinary
and Source
== File
:
915 self
._IntroBuildTargetList
.add(Target
)
917 # to avoid cyclic rule
918 if FileType
in RuleChain
:
919 EdkLogger
.error("build", ERROR_STATEMENT
, "Cyclic dependency detected while generating rule for %s" % str(Source
))
921 RuleChain
.add(FileType
)
922 SourceList
.extend(Target
.Outputs
)
924 # For each final target name, retrieve the corresponding TargetDescBlock instance.
925 for FTargetName
in FinalTargetName
:
926 for Target
in TargetList
:
927 if FTargetName
== Target
.Target
:
928 self
._FinalBuildTargetList
.add(Target
)
932 if self
._BuildTargets
is None:
933 self
._IntroBuildTargetList
= set()
934 self
._FinalBuildTargetList
= set()
935 self
._BuildTargets
= defaultdict(set)
936 self
._FileTypes
= defaultdict(set)
938 #TRICK: call SourceFileList property to apply build rule for source files
941 #TRICK: call _GetBinaryFileList to apply build rule for binary files
944 return self
._BuildTargets
947 def IntroTargetList(self
):
949 return self
._IntroBuildTargetList
952 def CodaTargetList(self
):
954 return self
._FinalBuildTargetList
959 return self
._FileTypes
961 ## Get the list of package object the module depends on and the Platform depends on
963 # @retval list The package object list
966 def DependentPackageList(self
):
967 return self
.PackageList
969 ## Return the list of auto-generated code file
971 # @retval list The list of auto-generated file
974 def AutoGenFileList(self
):
975 AutoGenUniIdf
= self
.BuildType
!= 'UEFI_HII'
976 UniStringBinBuffer
= BytesIO()
977 IdfGenBinBuffer
= BytesIO()
979 AutoGenC
= TemplateString()
980 AutoGenH
= TemplateString()
981 StringH
= TemplateString()
982 StringIdf
= TemplateString()
983 GenC
.CreateCode(self
, AutoGenC
, AutoGenH
, StringH
, AutoGenUniIdf
, UniStringBinBuffer
, StringIdf
, AutoGenUniIdf
, IdfGenBinBuffer
)
985 # AutoGen.c is generated if there are library classes in inf, or there are object files
987 if str(AutoGenC
) != "" and (len(self
.Module
.LibraryClasses
) > 0
988 or TAB_OBJECT_FILE
in self
.FileTypes
):
989 AutoFile
= PathClass(gAutoGenCodeFileName
, self
.DebugDir
)
990 RetVal
[AutoFile
] = str(AutoGenC
)
991 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
992 if str(AutoGenH
) != "":
993 AutoFile
= PathClass(gAutoGenHeaderFileName
, self
.DebugDir
)
994 RetVal
[AutoFile
] = str(AutoGenH
)
995 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
996 if str(StringH
) != "":
997 AutoFile
= PathClass(gAutoGenStringFileName
% {"module_name":self
.Name
}, self
.DebugDir
)
998 RetVal
[AutoFile
] = str(StringH
)
999 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
1000 if UniStringBinBuffer
is not None and UniStringBinBuffer
.getvalue() != b
"":
1001 AutoFile
= PathClass(gAutoGenStringFormFileName
% {"module_name":self
.Name
}, self
.OutputDir
)
1002 RetVal
[AutoFile
] = UniStringBinBuffer
.getvalue()
1003 AutoFile
.IsBinary
= True
1004 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
1005 if UniStringBinBuffer
is not None:
1006 UniStringBinBuffer
.close()
1007 if str(StringIdf
) != "":
1008 AutoFile
= PathClass(gAutoGenImageDefFileName
% {"module_name":self
.Name
}, self
.DebugDir
)
1009 RetVal
[AutoFile
] = str(StringIdf
)
1010 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
1011 if IdfGenBinBuffer
is not None and IdfGenBinBuffer
.getvalue() != b
"":
1012 AutoFile
= PathClass(gAutoGenIdfFileName
% {"module_name":self
.Name
}, self
.OutputDir
)
1013 RetVal
[AutoFile
] = IdfGenBinBuffer
.getvalue()
1014 AutoFile
.IsBinary
= True
1015 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
1016 if IdfGenBinBuffer
is not None:
1017 IdfGenBinBuffer
.close()
1020 ## Return the list of library modules explicitly or implicitly used by this module
1022 def DependentLibraryList(self
):
1023 # only merge library classes and PCD for non-library module
1026 return self
.PlatformInfo
.ApplyLibraryInstance(self
.Module
)
1028 ## Get the list of PCDs from current module
1030 # @retval list The list of PCD
1033 def ModulePcdList(self
):
1034 # apply PCD settings from platform
1035 RetVal
= self
.PlatformInfo
.ApplyPcdSetting(self
.Module
, self
.Module
.Pcds
)
1039 def _PcdComments(self
):
1040 ReVal
= OrderedListDict()
1041 ExtendCopyDictionaryLists(ReVal
, self
.Module
.PcdComments
)
1042 if not self
.IsLibrary
:
1043 for Library
in self
.DependentLibraryList
:
1044 ExtendCopyDictionaryLists(ReVal
, Library
.PcdComments
)
1047 ## Get the list of PCDs from dependent libraries
1049 # @retval list The list of PCD
1052 def LibraryPcdList(self
):
1057 # get PCDs from dependent libraries
1058 for Library
in self
.DependentLibraryList
:
1059 PcdsInLibrary
= OrderedDict()
1060 for Key
in Library
.Pcds
:
1061 # skip duplicated PCDs
1062 if Key
in self
.Module
.Pcds
or Key
in Pcds
:
1065 PcdsInLibrary
[Key
] = copy
.copy(Library
.Pcds
[Key
])
1066 RetVal
.extend(self
.PlatformInfo
.ApplyPcdSetting(self
.Module
, PcdsInLibrary
, Library
=Library
))
1069 ## Get the GUID value mapping
1071 # @retval dict The mapping between GUID cname and its value
1075 RetVal
= self
.Module
.Guids
1076 for Library
in self
.DependentLibraryList
:
1077 RetVal
.update(Library
.Guids
)
1078 ExtendCopyDictionaryLists(self
._GuidComments
, Library
.GuidComments
)
1079 ExtendCopyDictionaryLists(self
._GuidComments
, self
.Module
.GuidComments
)
1083 def GetGuidsUsedByPcd(self
):
1084 RetVal
= OrderedDict(self
.Module
.GetGuidsUsedByPcd())
1085 for Library
in self
.DependentLibraryList
:
1086 RetVal
.update(Library
.GetGuidsUsedByPcd())
1088 ## Get the protocol value mapping
1090 # @retval dict The mapping between protocol cname and its value
1093 def ProtocolList(self
):
1094 RetVal
= OrderedDict(self
.Module
.Protocols
)
1095 for Library
in self
.DependentLibraryList
:
1096 RetVal
.update(Library
.Protocols
)
1097 ExtendCopyDictionaryLists(self
._ProtocolComments
, Library
.ProtocolComments
)
1098 ExtendCopyDictionaryLists(self
._ProtocolComments
, self
.Module
.ProtocolComments
)
1101 ## Get the PPI value mapping
1103 # @retval dict The mapping between PPI cname and its value
1107 RetVal
= OrderedDict(self
.Module
.Ppis
)
1108 for Library
in self
.DependentLibraryList
:
1109 RetVal
.update(Library
.Ppis
)
1110 ExtendCopyDictionaryLists(self
._PpiComments
, Library
.PpiComments
)
1111 ExtendCopyDictionaryLists(self
._PpiComments
, self
.Module
.PpiComments
)
1114 ## Get the list of include search path
1116 # @retval list The list path
1119 def IncludePathList(self
):
1121 RetVal
.append(self
.MetaFile
.Dir
)
1122 RetVal
.append(self
.DebugDir
)
1124 for Package
in self
.PackageList
:
1125 PackageDir
= mws
.join(self
.WorkspaceDir
, Package
.MetaFile
.Dir
)
1126 if PackageDir
not in RetVal
:
1127 RetVal
.append(PackageDir
)
1128 IncludesList
= Package
.Includes
1129 if Package
._PrivateIncludes
:
1130 if not self
.MetaFile
.OriginalPath
.Path
.startswith(PackageDir
):
1131 IncludesList
= list(set(Package
.Includes
).difference(set(Package
._PrivateIncludes
)))
1132 for Inc
in IncludesList
:
1133 if Inc
not in RetVal
:
1134 RetVal
.append(str(Inc
))
1135 RetVal
.extend(self
.IncPathFromBuildOptions
)
1139 def IncPathFromBuildOptions(self
):
1141 for tool
in self
.BuildOption
:
1142 if 'FLAGS' in self
.BuildOption
[tool
]:
1143 flags
= self
.BuildOption
[tool
]['FLAGS']
1145 for flag
in flags
.split(" "):
1147 if flag
.startswith(("/I","-I")):
1149 if os
.path
.exists(flag
[2:]):
1150 IncPathList
.append(flag
[2:])
1154 if whitespace
and flag
:
1155 if os
.path
.exists(flag
):
1156 IncPathList
.append(flag
)
1161 def IncludePathLength(self
):
1162 return sum(len(inc
)+1 for inc
in self
.IncludePathList
)
1164 ## Get the list of include paths from the packages
1166 # @IncludesList list The list path
1169 def PackageIncludePathList(self
):
1171 for Package
in self
.PackageList
:
1172 PackageDir
= mws
.join(self
.WorkspaceDir
, Package
.MetaFile
.Dir
)
1173 IncludesList
= Package
.Includes
1174 if Package
._PrivateIncludes
:
1175 if not self
.MetaFile
.Path
.startswith(PackageDir
):
1176 IncludesList
= list(set(Package
.Includes
).difference(set(Package
._PrivateIncludes
)))
1179 ## Get HII EX PCDs which maybe used by VFR
1181 # efivarstore used by VFR may relate with HII EX PCDs
1182 # Get the variable name and GUID from efivarstore and HII EX PCD
1183 # List the HII EX PCDs in As Built INF if both name and GUID match.
1185 # @retval list HII EX PCDs
1187 def _GetPcdsMaybeUsedByVfr(self
):
1188 if not self
.SourceFileList
:
1192 for SrcFile
in self
.SourceFileList
:
1193 if SrcFile
.Ext
.lower() != '.vfr':
1195 Vfri
= os
.path
.join(self
.OutputDir
, SrcFile
.BaseName
+ '.i')
1196 if not os
.path
.exists(Vfri
):
1198 VfriFile
= open(Vfri
, 'r')
1199 Content
= VfriFile
.read()
1201 Pos
= Content
.find('efivarstore')
1204 # Make sure 'efivarstore' is the start of efivarstore statement
1205 # In case of the value of 'name' (name = efivarstore) is equal to 'efivarstore'
1208 while Index
>= 0 and Content
[Index
] in ' \t\r\n':
1210 if Index
>= 0 and Content
[Index
] != ';':
1211 Pos
= Content
.find('efivarstore', Pos
+ len('efivarstore'))
1214 # 'efivarstore' must be followed by name and guid
1216 Name
= gEfiVarStoreNamePattern
.search(Content
, Pos
)
1219 Guid
= gEfiVarStoreGuidPattern
.search(Content
, Pos
)
1222 NameArray
= _ConvertStringToByteArray('L"' + Name
.group(1) + '"')
1223 NameGuids
.add((NameArray
, GuidStructureStringToGuidString(Guid
.group(1))))
1224 Pos
= Content
.find('efivarstore', Name
.end())
1228 for Pcd
in self
.PlatformInfo
.Pcds
.values():
1229 if Pcd
.Type
!= TAB_PCDS_DYNAMIC_EX_HII
:
1231 for SkuInfo
in Pcd
.SkuInfoList
.values():
1232 Value
= GuidValue(SkuInfo
.VariableGuid
, self
.PlatformInfo
.PackageList
, self
.MetaFile
.Path
)
1235 Name
= _ConvertStringToByteArray(SkuInfo
.VariableName
)
1236 Guid
= GuidStructureStringToGuidString(Value
)
1237 if (Name
, Guid
) in NameGuids
and Pcd
not in HiiExPcds
:
1238 HiiExPcds
.append(Pcd
)
1243 def _GenOffsetBin(self
):
1245 for SourceFile
in self
.Module
.Sources
:
1246 if SourceFile
.Type
.upper() == ".VFR" :
1248 # search the .map file to find the offset of vfr binary in the PE32+/TE file.
1250 VfrUniBaseName
[SourceFile
.BaseName
] = (SourceFile
.BaseName
+ "Bin")
1251 elif SourceFile
.Type
.upper() == ".UNI" :
1253 # search the .map file to find the offset of Uni strings binary in the PE32+/TE file.
1255 VfrUniBaseName
["UniOffsetName"] = (self
.Name
+ "Strings")
1257 if not VfrUniBaseName
:
1259 MapFileName
= os
.path
.join(self
.OutputDir
, self
.Name
+ ".map")
1260 EfiFileName
= os
.path
.join(self
.OutputDir
, self
.Name
+ ".efi")
1261 VfrUniOffsetList
= GetVariableOffset(MapFileName
, EfiFileName
, list(VfrUniBaseName
.values()))
1262 if not VfrUniOffsetList
:
1265 OutputName
= '%sOffset.bin' % self
.Name
1266 UniVfrOffsetFileName
= os
.path
.join( self
.OutputDir
, OutputName
)
1269 fInputfile
= open(UniVfrOffsetFileName
, "wb+", 0)
1271 EdkLogger
.error("build", FILE_OPEN_FAILURE
, "File open failed for %s" % UniVfrOffsetFileName
, None)
1273 # Use a instance of BytesIO to cache data
1274 fStringIO
= BytesIO()
1276 for Item
in VfrUniOffsetList
:
1277 if (Item
[0].find("Strings") != -1):
1279 # UNI offset in image.
1281 # { 0x8913c5e0, 0x33f6, 0x4d86, { 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66 } }
1283 UniGuid
= b
'\xe0\xc5\x13\x89\xf63\x86M\x9b\xf1C\xef\x89\xfc\x06f'
1284 fStringIO
.write(UniGuid
)
1285 UniValue
= pack ('Q', int (Item
[1], 16))
1286 fStringIO
.write (UniValue
)
1289 # VFR binary offset in image.
1291 # { 0xd0bc7cb4, 0x6a47, 0x495f, { 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2 } };
1293 VfrGuid
= b
'\xb4|\xbc\xd0Gj_I\xaa\x11q\x07F\xda\x06\xa2'
1294 fStringIO
.write(VfrGuid
)
1295 VfrValue
= pack ('Q', int (Item
[1], 16))
1296 fStringIO
.write (VfrValue
)
1298 # write data into file.
1301 fInputfile
.write (fStringIO
.getvalue())
1303 EdkLogger
.error("build", FILE_WRITE_FAILURE
, "Write data to file %s failed, please check whether the "
1304 "file been locked or using by other applications." %UniVfrOffsetFileName
, None)
1311 def OutputFile(self
):
1314 for Root
, Dirs
, Files
in os
.walk(self
.BuildDir
):
1316 # lib file is already added through above CodaTargetList, skip it here
1317 if not (File
.lower().endswith('.obj') or File
.lower().endswith('.debug')):
1318 NewFile
= path
.join(Root
, File
)
1321 for Root
, Dirs
, Files
in os
.walk(self
.FfsOutputDir
):
1323 NewFile
= path
.join(Root
, File
)
1328 ## Create AsBuilt INF file the module
1330 def CreateAsBuiltInf(self
):
1332 if self
.IsAsBuiltInfCreated
:
1335 # Skip INF file generation for libraries
1339 # Skip the following code for modules with no source files
1340 if not self
.SourceFileList
:
1343 # Skip the following code for modules without any binary files
1344 if self
.BinaryFileList
:
1347 ### TODO: How to handles mixed source and binary modules
1349 # Find all DynamicEx and PatchableInModule PCDs used by this module and dependent libraries
1350 # Also find all packages that the DynamicEx PCDs depend on
1355 PcdTokenSpaceList
= []
1356 for Pcd
in self
.ModulePcdList
+ self
.LibraryPcdList
:
1357 if Pcd
.Type
== TAB_PCDS_PATCHABLE_IN_MODULE
:
1358 PatchablePcds
.append(Pcd
)
1359 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, TAB_PCDS_PATCHABLE_IN_MODULE
))
1360 elif Pcd
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
1363 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC_EX
))
1364 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC
))
1365 PcdTokenSpaceList
.append(Pcd
.TokenSpaceGuidCName
)
1366 GuidList
= OrderedDict(self
.GuidList
)
1367 for TokenSpace
in self
.GetGuidsUsedByPcd
:
1368 # If token space is not referred by patch PCD or Ex PCD, remove the GUID from GUID list
1369 # The GUIDs in GUIDs section should really be the GUIDs in source INF or referred by Ex an patch PCDs
1370 if TokenSpace
not in PcdTokenSpaceList
and TokenSpace
in GuidList
:
1371 GuidList
.pop(TokenSpace
)
1372 CheckList
= (GuidList
, self
.PpiList
, self
.ProtocolList
, PcdCheckList
)
1373 for Package
in self
.DerivedPackageList
:
1374 if Package
in Packages
:
1376 BeChecked
= (Package
.Guids
, Package
.Ppis
, Package
.Protocols
, Package
.Pcds
)
1378 for Index
in range(len(BeChecked
)):
1379 for Item
in CheckList
[Index
]:
1380 if Item
in BeChecked
[Index
]:
1381 Packages
.append(Package
)
1387 VfrPcds
= self
._GetPcdsMaybeUsedByVfr
()
1388 for Pkg
in self
.PlatformInfo
.PackageList
:
1391 for VfrPcd
in VfrPcds
:
1392 if ((VfrPcd
.TokenCName
, VfrPcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC_EX
) in Pkg
.Pcds
or
1393 (VfrPcd
.TokenCName
, VfrPcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC
) in Pkg
.Pcds
):
1394 Packages
.append(Pkg
)
1397 ModuleType
= SUP_MODULE_DXE_DRIVER
if self
.ModuleType
== SUP_MODULE_UEFI_DRIVER
and self
.DepexGenerated
else self
.ModuleType
1398 DriverType
= self
.PcdIsDriver
if self
.PcdIsDriver
else ''
1400 MDefs
= self
.Module
.Defines
1403 'module_name' : self
.Name
,
1404 'module_guid' : Guid
,
1405 'module_module_type' : ModuleType
,
1406 'module_version_string' : [MDefs
['VERSION_STRING']] if 'VERSION_STRING' in MDefs
else [],
1407 'pcd_is_driver_string' : [],
1408 'module_uefi_specification_version' : [],
1409 'module_pi_specification_version' : [],
1410 'module_entry_point' : self
.Module
.ModuleEntryPointList
,
1411 'module_unload_image' : self
.Module
.ModuleUnloadImageList
,
1412 'module_constructor' : self
.Module
.ConstructorList
,
1413 'module_destructor' : self
.Module
.DestructorList
,
1414 'module_shadow' : [MDefs
['SHADOW']] if 'SHADOW' in MDefs
else [],
1415 'module_pci_vendor_id' : [MDefs
['PCI_VENDOR_ID']] if 'PCI_VENDOR_ID' in MDefs
else [],
1416 'module_pci_device_id' : [MDefs
['PCI_DEVICE_ID']] if 'PCI_DEVICE_ID' in MDefs
else [],
1417 'module_pci_class_code' : [MDefs
['PCI_CLASS_CODE']] if 'PCI_CLASS_CODE' in MDefs
else [],
1418 'module_pci_revision' : [MDefs
['PCI_REVISION']] if 'PCI_REVISION' in MDefs
else [],
1419 'module_build_number' : [MDefs
['BUILD_NUMBER']] if 'BUILD_NUMBER' in MDefs
else [],
1420 'module_spec' : [MDefs
['SPEC']] if 'SPEC' in MDefs
else [],
1421 'module_uefi_hii_resource_section' : [MDefs
['UEFI_HII_RESOURCE_SECTION']] if 'UEFI_HII_RESOURCE_SECTION' in MDefs
else [],
1422 'module_uni_file' : [MDefs
['MODULE_UNI_FILE']] if 'MODULE_UNI_FILE' in MDefs
else [],
1423 'module_arch' : self
.Arch
,
1424 'package_item' : [Package
.MetaFile
.File
.replace('\\', '/') for Package
in Packages
],
1426 'patchablepcd_item' : [],
1428 'protocol_item' : [],
1432 'libraryclasses_item' : []
1435 if 'MODULE_UNI_FILE' in MDefs
:
1436 UNIFile
= os
.path
.join(self
.MetaFile
.Dir
, MDefs
['MODULE_UNI_FILE'])
1437 if os
.path
.isfile(UNIFile
):
1438 shutil
.copy2(UNIFile
, self
.OutputDir
)
1440 if self
.AutoGenVersion
> int(gInfSpecVersion
, 0):
1441 AsBuiltInfDict
['module_inf_version'] = '0x%08x' % self
.AutoGenVersion
1443 AsBuiltInfDict
['module_inf_version'] = gInfSpecVersion
1446 AsBuiltInfDict
['pcd_is_driver_string'].append(DriverType
)
1448 if 'UEFI_SPECIFICATION_VERSION' in self
.Specification
:
1449 AsBuiltInfDict
['module_uefi_specification_version'].append(self
.Specification
['UEFI_SPECIFICATION_VERSION'])
1450 if 'PI_SPECIFICATION_VERSION' in self
.Specification
:
1451 AsBuiltInfDict
['module_pi_specification_version'].append(self
.Specification
['PI_SPECIFICATION_VERSION'])
1453 OutputDir
= self
.OutputDir
.replace('\\', '/').strip('/')
1454 DebugDir
= self
.DebugDir
.replace('\\', '/').strip('/')
1455 for Item
in self
.CodaTargetList
:
1456 File
= Item
.Target
.Path
.replace('\\', '/').strip('/').replace(DebugDir
, '').replace(OutputDir
, '').strip('/')
1457 if os
.path
.isabs(File
):
1458 File
= File
.replace('\\', '/').strip('/').replace(OutputDir
, '').strip('/')
1459 if Item
.Target
.Ext
.lower() == '.aml':
1460 AsBuiltInfDict
['binary_item'].append('ASL|' + File
)
1461 elif Item
.Target
.Ext
.lower() == '.acpi':
1462 AsBuiltInfDict
['binary_item'].append('ACPI|' + File
)
1463 elif Item
.Target
.Ext
.lower() == '.efi':
1464 AsBuiltInfDict
['binary_item'].append('PE32|' + self
.Name
+ '.efi')
1466 AsBuiltInfDict
['binary_item'].append('BIN|' + File
)
1467 if not self
.DepexGenerated
:
1468 DepexFile
= os
.path
.join(self
.OutputDir
, self
.Name
+ '.depex')
1469 if os
.path
.exists(DepexFile
):
1470 self
.DepexGenerated
= True
1471 if self
.DepexGenerated
:
1472 if self
.ModuleType
in [SUP_MODULE_PEIM
]:
1473 AsBuiltInfDict
['binary_item'].append('PEI_DEPEX|' + self
.Name
+ '.depex')
1474 elif self
.ModuleType
in [SUP_MODULE_DXE_DRIVER
, SUP_MODULE_DXE_RUNTIME_DRIVER
, SUP_MODULE_DXE_SAL_DRIVER
, SUP_MODULE_UEFI_DRIVER
]:
1475 AsBuiltInfDict
['binary_item'].append('DXE_DEPEX|' + self
.Name
+ '.depex')
1476 elif self
.ModuleType
in [SUP_MODULE_DXE_SMM_DRIVER
]:
1477 AsBuiltInfDict
['binary_item'].append('SMM_DEPEX|' + self
.Name
+ '.depex')
1479 Bin
= self
._GenOffsetBin
()
1481 AsBuiltInfDict
['binary_item'].append('BIN|%s' % Bin
)
1483 for Root
, Dirs
, Files
in os
.walk(OutputDir
):
1485 if File
.lower().endswith('.pdb'):
1486 AsBuiltInfDict
['binary_item'].append('DISPOSABLE|' + File
)
1487 HeaderComments
= self
.Module
.HeaderComments
1489 for Index
in range(len(HeaderComments
)):
1490 if HeaderComments
[Index
].find('@BinaryHeader') != -1:
1491 HeaderComments
[Index
] = HeaderComments
[Index
].replace('@BinaryHeader', '@file')
1494 AsBuiltInfDict
['header_comments'] = '\n'.join(HeaderComments
[StartPos
:]).replace(':#', '://')
1495 AsBuiltInfDict
['tail_comments'] = '\n'.join(self
.Module
.TailComments
)
1498 (self
.ProtocolList
, self
._ProtocolComments
, 'protocol_item'),
1499 (self
.PpiList
, self
._PpiComments
, 'ppi_item'),
1500 (GuidList
, self
._GuidComments
, 'guid_item')
1502 for Item
in GenList
:
1503 for CName
in Item
[0]:
1504 Comments
= '\n '.join(Item
[1][CName
]) if CName
in Item
[1] else ''
1505 Entry
= Comments
+ '\n ' + CName
if Comments
else CName
1506 AsBuiltInfDict
[Item
[2]].append(Entry
)
1507 PatchList
= parsePcdInfoFromMapFile(
1508 os
.path
.join(self
.OutputDir
, self
.Name
+ '.map'),
1509 os
.path
.join(self
.OutputDir
, self
.Name
+ '.efi')
1512 for Pcd
in PatchablePcds
:
1513 TokenCName
= Pcd
.TokenCName
1514 for PcdItem
in GlobalData
.MixedPcd
:
1515 if (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
1516 TokenCName
= PcdItem
[0]
1518 for PatchPcd
in PatchList
:
1519 if TokenCName
== PatchPcd
[0]:
1524 if Pcd
.DatumType
== 'BOOLEAN':
1525 BoolValue
= Pcd
.DefaultValue
.upper()
1526 if BoolValue
== 'TRUE':
1527 Pcd
.DefaultValue
= '1'
1528 elif BoolValue
== 'FALSE':
1529 Pcd
.DefaultValue
= '0'
1531 if Pcd
.DatumType
in TAB_PCD_NUMERIC_TYPES
:
1532 HexFormat
= '0x%02x'
1533 if Pcd
.DatumType
== TAB_UINT16
:
1534 HexFormat
= '0x%04x'
1535 elif Pcd
.DatumType
== TAB_UINT32
:
1536 HexFormat
= '0x%08x'
1537 elif Pcd
.DatumType
== TAB_UINT64
:
1538 HexFormat
= '0x%016x'
1539 PcdValue
= HexFormat
% int(Pcd
.DefaultValue
, 0)
1541 if Pcd
.MaxDatumSize
is None or Pcd
.MaxDatumSize
== '':
1542 EdkLogger
.error("build", AUTOGEN_ERROR
,
1543 "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
1545 ArraySize
= int(Pcd
.MaxDatumSize
, 0)
1546 PcdValue
= Pcd
.DefaultValue
1547 if PcdValue
[0] != '{':
1549 if PcdValue
[0] == 'L':
1551 PcdValue
= PcdValue
.lstrip('L')
1552 PcdValue
= eval(PcdValue
)
1554 for Index
in range(0, len(PcdValue
)):
1556 CharVal
= ord(PcdValue
[Index
])
1557 NewValue
= NewValue
+ '0x%02x' % (CharVal
& 0x00FF) + ', ' \
1558 + '0x%02x' % (CharVal
>> 8) + ', '
1560 NewValue
= NewValue
+ '0x%02x' % (ord(PcdValue
[Index
]) % 0x100) + ', '
1563 Padding
= Padding
* 2
1564 ArraySize
= ArraySize
// 2
1565 if ArraySize
< (len(PcdValue
) + 1):
1566 if Pcd
.MaxSizeUserSet
:
1567 EdkLogger
.error("build", AUTOGEN_ERROR
,
1568 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
1571 ArraySize
= len(PcdValue
) + 1
1572 if ArraySize
> len(PcdValue
) + 1:
1573 NewValue
= NewValue
+ Padding
* (ArraySize
- len(PcdValue
) - 1)
1574 PcdValue
= NewValue
+ Padding
.strip().rstrip(',') + '}'
1575 elif len(PcdValue
.split(',')) <= ArraySize
:
1576 PcdValue
= PcdValue
.rstrip('}') + ', 0x00' * (ArraySize
- len(PcdValue
.split(',')))
1579 if Pcd
.MaxSizeUserSet
:
1580 EdkLogger
.error("build", AUTOGEN_ERROR
,
1581 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
1584 ArraySize
= len(PcdValue
) + 1
1585 PcdItem
= '%s.%s|%s|0x%X' % \
1586 (Pcd
.TokenSpaceGuidCName
, TokenCName
, PcdValue
, PatchPcd
[1])
1588 if (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) in self
._PcdComments
:
1589 PcdComments
= '\n '.join(self
._PcdComments
[Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
])
1591 PcdItem
= PcdComments
+ '\n ' + PcdItem
1592 AsBuiltInfDict
['patchablepcd_item'].append(PcdItem
)
1594 for Pcd
in Pcds
+ VfrPcds
:
1597 TokenCName
= Pcd
.TokenCName
1598 for PcdItem
in GlobalData
.MixedPcd
:
1599 if (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
1600 TokenCName
= PcdItem
[0]
1602 if Pcd
.Type
== TAB_PCDS_DYNAMIC_EX_HII
:
1603 for SkuName
in Pcd
.SkuInfoList
:
1604 SkuInfo
= Pcd
.SkuInfoList
[SkuName
]
1605 HiiInfo
= '## %s|%s|%s' % (SkuInfo
.VariableName
, SkuInfo
.VariableGuid
, SkuInfo
.VariableOffset
)
1607 if (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) in self
._PcdComments
:
1608 PcdCommentList
= self
._PcdComments
[Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
][:]
1612 for Index
, Comment
in enumerate(PcdCommentList
):
1613 for Usage
in UsageList
:
1614 if Comment
.find(Usage
) != -1:
1618 if UsageIndex
!= -1:
1619 PcdCommentList
[UsageIndex
] = '## %s %s %s' % (UsageStr
, HiiInfo
, PcdCommentList
[UsageIndex
].replace(UsageStr
, ''))
1621 PcdCommentList
.append('## UNDEFINED ' + HiiInfo
)
1622 PcdComments
= '\n '.join(PcdCommentList
)
1623 PcdEntry
= Pcd
.TokenSpaceGuidCName
+ '.' + TokenCName
1625 PcdEntry
= PcdComments
+ '\n ' + PcdEntry
1626 AsBuiltInfDict
['pcd_item'].append(PcdEntry
)
1627 for Item
in self
.BuildOption
:
1628 if 'FLAGS' in self
.BuildOption
[Item
]:
1629 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()))
1631 # Generated LibraryClasses section in comments.
1632 for Library
in self
.LibraryAutoGenList
:
1633 AsBuiltInfDict
['libraryclasses_item'].append(Library
.MetaFile
.File
.replace('\\', '/'))
1635 # Generated UserExtensions TianoCore section.
1636 # All tianocore user extensions are copied.
1638 for TianoCore
in self
._GetTianoCoreUserExtensionList
():
1639 UserExtStr
+= '\n'.join(TianoCore
)
1640 ExtensionFile
= os
.path
.join(self
.MetaFile
.Dir
, TianoCore
[1])
1641 if os
.path
.isfile(ExtensionFile
):
1642 shutil
.copy2(ExtensionFile
, self
.OutputDir
)
1643 AsBuiltInfDict
['userextension_tianocore_item'] = UserExtStr
1645 # Generated depex expression section in comments.
1646 DepexExpression
= self
._GetDepexExpresionString
()
1647 AsBuiltInfDict
['depexsection_item'] = DepexExpression
if DepexExpression
else ''
1649 AsBuiltInf
= TemplateString()
1650 AsBuiltInf
.Append(gAsBuiltInfHeaderString
.Replace(AsBuiltInfDict
))
1652 SaveFileOnChange(os
.path
.join(self
.OutputDir
, self
.Name
+ '.inf'), str(AsBuiltInf
), False)
1654 self
.IsAsBuiltInfCreated
= True
1656 def CacheCopyFile(self
, DestDir
, SourceDir
, File
):
1657 if os
.path
.isdir(File
):
1660 sub_dir
= os
.path
.relpath(File
, SourceDir
)
1661 destination_file
= os
.path
.join(DestDir
, sub_dir
)
1662 destination_dir
= os
.path
.dirname(destination_file
)
1663 CreateDirectory(destination_dir
)
1665 CopyFileOnChange(File
, destination_dir
)
1667 EdkLogger
.quiet("[cache warning]: fail to copy file:%s to folder:%s" % (File
, destination_dir
))
1670 def CopyModuleToCache(self
):
1671 # Find the MakeHashStr and PreMakeHashStr from latest MakeHashFileList
1672 # and PreMakeHashFileList files
1674 PreMakeHashStr
= None
1676 PreMakeTimeStamp
= 0
1677 Files
= [f
for f
in os
.listdir(LongFilePath(self
.BuildDir
)) if path
.isfile(LongFilePath(path
.join(self
.BuildDir
, f
)))]
1679 if ".MakeHashFileList." in File
:
1680 #find lastest file through time stamp
1681 FileTimeStamp
= os
.stat(LongFilePath(path
.join(self
.BuildDir
, File
)))[8]
1682 if FileTimeStamp
> MakeTimeStamp
:
1683 MakeTimeStamp
= FileTimeStamp
1684 MakeHashStr
= File
.split('.')[-1]
1685 if len(MakeHashStr
) != 32:
1686 EdkLogger
.quiet("[cache error]: wrong MakeHashFileList file:%s" % (File
))
1687 if ".PreMakeHashFileList." in File
:
1688 FileTimeStamp
= os
.stat(LongFilePath(path
.join(self
.BuildDir
, File
)))[8]
1689 if FileTimeStamp
> PreMakeTimeStamp
:
1690 PreMakeTimeStamp
= FileTimeStamp
1691 PreMakeHashStr
= File
.split('.')[-1]
1692 if len(PreMakeHashStr
) != 32:
1693 EdkLogger
.quiet("[cache error]: wrong PreMakeHashFileList file:%s" % (File
))
1696 EdkLogger
.quiet("[cache error]: No MakeHashFileList file for module:%s[%s]" % (self
.MetaFile
.Path
, self
.Arch
))
1698 if not PreMakeHashStr
:
1699 EdkLogger
.quiet("[cache error]: No PreMakeHashFileList file for module:%s[%s]" % (self
.MetaFile
.Path
, self
.Arch
))
1702 # Create Cache destination dirs
1703 FileDir
= path
.join(GlobalData
.gBinCacheDest
, self
.PlatformInfo
.OutputDir
, self
.BuildTarget
+ "_" + self
.ToolChain
, self
.Arch
, self
.SourceDir
, self
.MetaFile
.BaseName
)
1704 FfsDir
= path
.join(GlobalData
.gBinCacheDest
, self
.PlatformInfo
.OutputDir
, self
.BuildTarget
+ "_" + self
.ToolChain
, TAB_FV_DIRECTORY
, "Ffs", self
.Guid
+ self
.Name
)
1705 CacheFileDir
= path
.join(FileDir
, MakeHashStr
)
1706 CacheFfsDir
= path
.join(FfsDir
, MakeHashStr
)
1707 CreateDirectory (CacheFileDir
)
1708 CreateDirectory (CacheFfsDir
)
1710 # Create ModuleHashPair file to support multiple version cache together
1711 ModuleHashPair
= path
.join(FileDir
, self
.Name
+ ".ModuleHashPair")
1712 ModuleHashPairList
= [] # tuple list: [tuple(PreMakefileHash, MakeHash)]
1713 if os
.path
.exists(ModuleHashPair
):
1714 with
open(ModuleHashPair
, 'r') as f
:
1715 ModuleHashPairList
= json
.load(f
)
1716 if not (PreMakeHashStr
, MakeHashStr
) in set(map(tuple, ModuleHashPairList
)):
1717 ModuleHashPairList
.insert(0, (PreMakeHashStr
, MakeHashStr
))
1718 with
open(ModuleHashPair
, 'w') as f
:
1719 json
.dump(ModuleHashPairList
, f
, indent
=2)
1721 # Copy files to Cache destination dirs
1722 if not self
.OutputFile
:
1723 Ma
= self
.BuildDatabase
[self
.MetaFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1724 self
.OutputFile
= Ma
.Binaries
1725 for File
in self
.OutputFile
:
1726 if File
.startswith(os
.path
.abspath(self
.FfsOutputDir
)+os
.sep
):
1727 self
.CacheCopyFile(CacheFfsDir
, self
.FfsOutputDir
, File
)
1729 if self
.Name
+ ".autogen.hash." in File
or \
1730 self
.Name
+ ".autogen.hashchain." in File
or \
1731 self
.Name
+ ".hash." in File
or \
1732 self
.Name
+ ".hashchain." in File
or \
1733 self
.Name
+ ".PreMakeHashFileList." in File
or \
1734 self
.Name
+ ".MakeHashFileList." in File
:
1735 self
.CacheCopyFile(FileDir
, self
.BuildDir
, File
)
1737 self
.CacheCopyFile(CacheFileDir
, self
.BuildDir
, File
)
1738 ## Create makefile for the module and its dependent libraries
1740 # @param CreateLibraryMakeFile Flag indicating if or not the makefiles of
1741 # dependent libraries will be created
1743 @cached_class_function
1744 def CreateMakeFile(self
, CreateLibraryMakeFile
=True, GenFfsList
= []):
1746 # nest this function inside it's only caller.
1747 def CreateTimeStamp():
1748 FileSet
= {self
.MetaFile
.Path
}
1750 for SourceFile
in self
.Module
.Sources
:
1751 FileSet
.add (SourceFile
.Path
)
1753 for Lib
in self
.DependentLibraryList
:
1754 FileSet
.add (Lib
.MetaFile
.Path
)
1756 for f
in self
.AutoGenDepSet
:
1757 FileSet
.add (f
.Path
)
1759 if os
.path
.exists (self
.TimeStampPath
):
1760 os
.remove (self
.TimeStampPath
)
1762 SaveFileOnChange(self
.TimeStampPath
, "\n".join(FileSet
), False)
1764 # Ignore generating makefile when it is a binary module
1765 if self
.IsBinaryModule
:
1768 self
.GenFfsList
= GenFfsList
1770 if not self
.IsLibrary
and CreateLibraryMakeFile
:
1771 for LibraryAutoGen
in self
.LibraryAutoGenList
:
1772 LibraryAutoGen
.CreateMakeFile()
1774 # CanSkip uses timestamps to determine build skipping
1778 if len(self
.CustomMakefile
) == 0:
1779 Makefile
= GenMake
.ModuleMakefile(self
)
1781 Makefile
= GenMake
.CustomMakefile(self
)
1782 if Makefile
.Generate():
1783 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated makefile for module %s [%s]" %
1784 (self
.Name
, self
.Arch
))
1786 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Skipped the generation of makefile for module %s [%s]" %
1787 (self
.Name
, self
.Arch
))
1791 MakefileType
= Makefile
._FileType
1792 MakefileName
= Makefile
._FILE
_NAME
_[MakefileType
]
1793 MakefilePath
= os
.path
.join(self
.MakeFileDir
, MakefileName
)
1794 FilePath
= path
.join(self
.BuildDir
, self
.Name
+ ".makefile")
1795 SaveFileOnChange(FilePath
, MakefilePath
, False)
1797 def CopyBinaryFiles(self
):
1798 for File
in self
.Module
.Binaries
:
1800 DstPath
= os
.path
.join(self
.OutputDir
, os
.path
.basename(SrcPath
))
1801 CopyLongFilePath(SrcPath
, DstPath
)
1802 ## Create autogen code for the module and its dependent libraries
1804 # @param CreateLibraryCodeFile Flag indicating if or not the code of
1805 # dependent libraries will be created
1807 def CreateCodeFile(self
, CreateLibraryCodeFile
=True):
1809 if self
.IsCodeFileCreated
:
1812 # Need to generate PcdDatabase even PcdDriver is binarymodule
1813 if self
.IsBinaryModule
and self
.PcdIsDriver
!= '':
1814 CreatePcdDatabaseCode(self
, TemplateString(), TemplateString())
1816 if self
.IsBinaryModule
:
1818 self
.CopyBinaryFiles()
1821 if not self
.IsLibrary
and CreateLibraryCodeFile
:
1822 for LibraryAutoGen
in self
.LibraryAutoGenList
:
1823 LibraryAutoGen
.CreateCodeFile()
1825 self
.LibraryAutoGenList
1827 IgoredAutoGenList
= []
1829 for File
in self
.AutoGenFileList
:
1830 if GenC
.Generate(File
.Path
, self
.AutoGenFileList
[File
], File
.IsBinary
):
1831 AutoGenList
.append(str(File
))
1833 IgoredAutoGenList
.append(str(File
))
1836 for ModuleType
in self
.DepexList
:
1837 # Ignore empty [depex] section or [depex] section for SUP_MODULE_USER_DEFINED module
1838 if len(self
.DepexList
[ModuleType
]) == 0 or ModuleType
== SUP_MODULE_USER_DEFINED
or ModuleType
== SUP_MODULE_HOST_APPLICATION
:
1841 Dpx
= GenDepex
.DependencyExpression(self
.DepexList
[ModuleType
], ModuleType
, True)
1842 DpxFile
= gAutoGenDepexFileName
% {"module_name" : self
.Name
}
1844 if len(Dpx
.PostfixNotation
) != 0:
1845 self
.DepexGenerated
= True
1847 if Dpx
.Generate(path
.join(self
.OutputDir
, DpxFile
)):
1848 AutoGenList
.append(str(DpxFile
))
1850 IgoredAutoGenList
.append(str(DpxFile
))
1852 if IgoredAutoGenList
== []:
1853 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated [%s] files for module %s [%s]" %
1854 (" ".join(AutoGenList
), self
.Name
, self
.Arch
))
1855 elif AutoGenList
== []:
1856 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Skipped the generation of [%s] files for module %s [%s]" %
1857 (" ".join(IgoredAutoGenList
), self
.Name
, self
.Arch
))
1859 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated [%s] (skipped %s) files for module %s [%s]" %
1860 (" ".join(AutoGenList
), " ".join(IgoredAutoGenList
), self
.Name
, self
.Arch
))
1862 self
.IsCodeFileCreated
= True
1866 ## Summarize the ModuleAutoGen objects of all libraries used by this module
1868 def LibraryAutoGenList(self
):
1870 for Library
in self
.DependentLibraryList
:
1877 self
.PlatformInfo
.MetaFile
,
1881 if La
not in RetVal
:
1883 for Lib
in La
.CodaTargetList
:
1884 self
._ApplyBuildRule
(Lib
.Target
, TAB_UNKNOWN_FILE
)
1887 def GenCMakeHash(self
):
1888 # GenCMakeHash can only be called in --binary-destination
1889 # Never called in multiprocessing and always directly save result in main process,
1890 # so no need remote dict to share the gCMakeHashFile result with main process
1892 DependencyFileSet
= set()
1894 if self
.AutoGenFileList
:
1895 for File
in set(self
.AutoGenFileList
):
1896 DependencyFileSet
.add(File
)
1899 abspath
= path
.join(self
.BuildDir
, self
.Name
+ ".makefile")
1901 with
open(LongFilePath(abspath
),"r") as fd
:
1902 lines
= fd
.readlines()
1903 except Exception as e
:
1904 EdkLogger
.error("build",FILE_NOT_FOUND
, "%s doesn't exist" % abspath
, ExtraData
=str(e
), RaiseError
=False)
1906 DependencyFileSet
.update(lines
)
1908 # Caculate all above dependency files hash
1909 # Initialze hash object
1912 for File
in sorted(DependencyFileSet
, key
=lambda x
: str(x
)):
1913 if not path
.exists(LongFilePath(str(File
))):
1914 EdkLogger
.quiet("[cache warning]: header file %s is missing for module: %s[%s]" % (File
, self
.MetaFile
.Path
, self
.Arch
))
1916 with
open(LongFilePath(str(File
)), 'rb') as f
:
1919 FileList
.append((str(File
), hashlib
.md5(Content
).hexdigest()))
1921 HashChainFile
= path
.join(self
.BuildDir
, self
.Name
+ ".autogen.hashchain." + m
.hexdigest())
1922 GlobalData
.gCMakeHashFile
[(self
.MetaFile
.Path
, self
.Arch
)] = HashChainFile
1924 with
open(LongFilePath(HashChainFile
), 'w') as f
:
1925 json
.dump(FileList
, f
, indent
=2)
1927 EdkLogger
.quiet("[cache warning]: fail to save hashchain file:%s" % HashChainFile
)
1930 def GenModuleHash(self
):
1931 # GenModuleHash only called after autogen phase
1932 # Never called in multiprocessing and always directly save result in main process,
1933 # so no need remote dict to share the gModuleHashFile result with main process
1935 # GenPreMakefileHashList consume no dict.
1936 # GenPreMakefileHashList produce local gModuleHashFile dict.
1938 DependencyFileSet
= set()
1939 # Add Module Meta file
1940 DependencyFileSet
.add(self
.MetaFile
.Path
)
1942 # Add Module's source files
1943 if self
.SourceFileList
:
1944 for File
in set(self
.SourceFileList
):
1945 DependencyFileSet
.add(File
.Path
)
1947 # Add modules's include header files
1948 # Directly use the deps.txt file in the module BuildDir
1949 abspath
= path
.join(self
.BuildDir
, "deps.txt")
1952 with
open(LongFilePath(abspath
),"r") as fd
:
1953 lines
= fd
.readlines()
1955 rt
= set([item
.lstrip().strip("\n") for item
in lines
if item
.strip("\n").endswith(".h")])
1956 except Exception as e
:
1957 EdkLogger
.error("build",FILE_NOT_FOUND
, "%s doesn't exist" % abspath
, ExtraData
=str(e
), RaiseError
=False)
1960 DependencyFileSet
.update(rt
)
1963 # Caculate all above dependency files hash
1964 # Initialze hash object
1967 BuildDirStr
= path
.abspath(self
.BuildDir
).lower()
1968 for File
in sorted(DependencyFileSet
, key
=lambda x
: str(x
)):
1969 # Skip the AutoGen files in BuildDir which already been
1970 # included in .autogen.hash. file
1971 if BuildDirStr
in path
.abspath(File
).lower():
1973 if not path
.exists(LongFilePath(File
)):
1974 EdkLogger
.quiet("[cache warning]: header file %s is missing for module: %s[%s]" % (File
, self
.MetaFile
.Path
, self
.Arch
))
1976 with
open(LongFilePath(File
), 'rb') as f
:
1979 FileList
.append((File
, hashlib
.md5(Content
).hexdigest()))
1981 HashChainFile
= path
.join(self
.BuildDir
, self
.Name
+ ".hashchain." + m
.hexdigest())
1982 GlobalData
.gModuleHashFile
[(self
.MetaFile
.Path
, self
.Arch
)] = HashChainFile
1984 with
open(LongFilePath(HashChainFile
), 'w') as f
:
1985 json
.dump(FileList
, f
, indent
=2)
1987 EdkLogger
.quiet("[cache warning]: fail to save hashchain file:%s" % HashChainFile
)
1990 def GenPreMakefileHashList(self
):
1991 # GenPreMakefileHashList consume below dicts:
1995 # GenPreMakefileHashList produce no dict.
1996 # gModuleHashFile items might be produced in multiprocessing, so
1997 # need check gModuleHashFile remote dict
1999 # skip binary module
2000 if self
.IsBinaryModule
:
2005 # Add Platform level hash
2006 HashFile
= GlobalData
.gPlatformHashFile
2007 if path
.exists(LongFilePath(HashFile
)):
2008 FileList
.append(HashFile
)
2009 m
.update(HashFile
.encode('utf-8'))
2011 EdkLogger
.quiet("[cache warning]: No Platform HashFile: %s" % HashFile
)
2013 # Add Package level hash
2014 if self
.DependentPackageList
:
2015 for Pkg
in sorted(self
.DependentPackageList
, key
=lambda x
: x
.PackageName
):
2016 if not (Pkg
.PackageName
, Pkg
.Arch
) in GlobalData
.gPackageHashFile
:
2017 EdkLogger
.quiet("[cache warning]:No Package %s for module %s[%s]" % (Pkg
.PackageName
, self
.MetaFile
.Path
, self
.Arch
))
2019 HashFile
= GlobalData
.gPackageHashFile
[(Pkg
.PackageName
, Pkg
.Arch
)]
2020 if path
.exists(LongFilePath(HashFile
)):
2021 FileList
.append(HashFile
)
2022 m
.update(HashFile
.encode('utf-8'))
2024 EdkLogger
.quiet("[cache warning]:No Package HashFile: %s" % HashFile
)
2027 # GenPreMakefileHashList needed in both --binary-destination
2028 # and --hash. And --hash might save ModuleHashFile in remote dict
2029 # during multiprocessing.
2030 if (self
.MetaFile
.Path
, self
.Arch
) in GlobalData
.gModuleHashFile
:
2031 HashFile
= GlobalData
.gModuleHashFile
[(self
.MetaFile
.Path
, self
.Arch
)]
2033 EdkLogger
.quiet("[cache error]:No ModuleHashFile for module: %s[%s]" % (self
.MetaFile
.Path
, self
.Arch
))
2034 if path
.exists(LongFilePath(HashFile
)):
2035 FileList
.append(HashFile
)
2036 m
.update(HashFile
.encode('utf-8'))
2038 EdkLogger
.quiet("[cache warning]:No Module HashFile: %s" % HashFile
)
2041 if self
.LibraryAutoGenList
:
2042 for Lib
in sorted(self
.LibraryAutoGenList
, key
=lambda x
: x
.MetaFile
.Path
):
2044 if (Lib
.MetaFile
.Path
, Lib
.Arch
) in GlobalData
.gModuleHashFile
:
2045 HashFile
= GlobalData
.gModuleHashFile
[(Lib
.MetaFile
.Path
, Lib
.Arch
)]
2047 EdkLogger
.quiet("[cache error]:No ModuleHashFile for lib: %s[%s]" % (Lib
.MetaFile
.Path
, Lib
.Arch
))
2048 if path
.exists(LongFilePath(HashFile
)):
2049 FileList
.append(HashFile
)
2050 m
.update(HashFile
.encode('utf-8'))
2052 EdkLogger
.quiet("[cache warning]:No Lib HashFile: %s" % HashFile
)
2054 # Save PreMakeHashFileList
2055 FilePath
= path
.join(self
.BuildDir
, self
.Name
+ ".PreMakeHashFileList." + m
.hexdigest())
2057 with
open(LongFilePath(FilePath
), 'w') as f
:
2058 json
.dump(FileList
, f
, indent
=0)
2060 EdkLogger
.quiet("[cache warning]: fail to save PreMake HashFileList: %s" % FilePath
)
2062 def GenMakefileHashList(self
):
2063 # GenMakefileHashList only need in --binary-destination which will
2064 # everything in local dict. So don't need check remote dict.
2066 # skip binary module
2067 if self
.IsBinaryModule
:
2073 HashFile
= GlobalData
.gCMakeHashFile
[(self
.MetaFile
.Path
, self
.Arch
)]
2074 if path
.exists(LongFilePath(HashFile
)):
2075 FileList
.append(HashFile
)
2076 m
.update(HashFile
.encode('utf-8'))
2078 EdkLogger
.quiet("[cache warning]:No AutoGen HashFile: %s" % HashFile
)
2081 if (self
.MetaFile
.Path
, self
.Arch
) in GlobalData
.gModuleHashFile
:
2082 HashFile
= GlobalData
.gModuleHashFile
[(self
.MetaFile
.Path
, self
.Arch
)]
2084 EdkLogger
.quiet("[cache error]:No ModuleHashFile for module: %s[%s]" % (self
.MetaFile
.Path
, self
.Arch
))
2085 if path
.exists(LongFilePath(HashFile
)):
2086 FileList
.append(HashFile
)
2087 m
.update(HashFile
.encode('utf-8'))
2089 EdkLogger
.quiet("[cache warning]:No Module HashFile: %s" % HashFile
)
2092 if self
.LibraryAutoGenList
:
2093 for Lib
in sorted(self
.LibraryAutoGenList
, key
=lambda x
: x
.MetaFile
.Path
):
2094 if (Lib
.MetaFile
.Path
, Lib
.Arch
) in GlobalData
.gModuleHashFile
:
2095 HashFile
= GlobalData
.gModuleHashFile
[(Lib
.MetaFile
.Path
, Lib
.Arch
)]
2097 EdkLogger
.quiet("[cache error]:No ModuleHashFile for lib: %s[%s]" % (Lib
.MetaFile
.Path
, Lib
.Arch
))
2098 if path
.exists(LongFilePath(HashFile
)):
2099 FileList
.append(HashFile
)
2100 m
.update(HashFile
.encode('utf-8'))
2102 EdkLogger
.quiet("[cache warning]:No Lib HashFile: %s" % HashFile
)
2104 # Save MakeHashFileList
2105 FilePath
= path
.join(self
.BuildDir
, self
.Name
+ ".MakeHashFileList." + m
.hexdigest())
2107 with
open(LongFilePath(FilePath
), 'w') as f
:
2108 json
.dump(FileList
, f
, indent
=0)
2110 EdkLogger
.quiet("[cache warning]: fail to save Make HashFileList: %s" % FilePath
)
2112 def CheckHashChainFile(self
, HashChainFile
):
2113 # Assume the HashChainFile basename format is the 'x.hashchain.16BytesHexStr'
2114 # The x is module name and the 16BytesHexStr is md5 hexdigest of
2115 # all hashchain files content
2116 HashStr
= HashChainFile
.split('.')[-1]
2117 if len(HashStr
) != 32:
2118 EdkLogger
.quiet("[cache error]: wrong format HashChainFile:%s" % (File
))
2122 with
open(LongFilePath(HashChainFile
), 'r') as f
:
2123 HashChainList
= json
.load(f
)
2125 EdkLogger
.quiet("[cache error]: fail to load HashChainFile: %s" % HashChainFile
)
2128 # Print the different file info
2129 # print(HashChainFile)
2130 for idx
, (SrcFile
, SrcHash
) in enumerate (HashChainList
):
2131 if SrcFile
in GlobalData
.gFileHashDict
:
2132 DestHash
= GlobalData
.gFileHashDict
[SrcFile
]
2135 with
open(LongFilePath(SrcFile
), 'rb') as f
:
2137 DestHash
= hashlib
.md5(Content
).hexdigest()
2138 GlobalData
.gFileHashDict
[SrcFile
] = DestHash
2139 except IOError as X
:
2140 # cache miss if SrcFile is removed in new version code
2141 GlobalData
.gFileHashDict
[SrcFile
] = 0
2142 EdkLogger
.quiet("[cache insight]: first cache miss file in %s is %s" % (HashChainFile
, SrcFile
))
2144 if SrcHash
!= DestHash
:
2145 EdkLogger
.quiet("[cache insight]: first cache miss file in %s is %s" % (HashChainFile
, SrcFile
))
2150 ## Decide whether we can skip the left autogen and make process
2151 def CanSkipbyMakeCache(self
):
2152 # For --binary-source only
2153 # CanSkipbyMakeCache consume below dicts:
2154 # gModuleMakeCacheStatus
2156 # GenPreMakefileHashList produce gModuleMakeCacheStatus, gModuleHashFile dict.
2157 # all these dicts might be produced in multiprocessing, so
2158 # need check these remote dict
2160 if not GlobalData
.gBinCacheSource
:
2163 if (self
.MetaFile
.Path
, self
.Arch
) in GlobalData
.gModuleMakeCacheStatus
:
2164 return GlobalData
.gModuleMakeCacheStatus
[(self
.MetaFile
.Path
, self
.Arch
)]
2166 # If Module is binary, which has special build rule, do not skip by cache.
2167 if self
.IsBinaryModule
:
2168 print("[cache miss]: MakeCache: Skip BinaryModule:", self
.MetaFile
.Path
, self
.Arch
)
2169 GlobalData
.gModuleMakeCacheStatus
[(self
.MetaFile
.Path
, self
.Arch
)] = False
2172 # see .inc as binary file, do not skip by hash
2173 for f_ext
in self
.SourceFileList
:
2174 if '.inc' in str(f_ext
):
2175 print("[cache miss]: MakeCache: Skip '.inc' File:", self
.MetaFile
.Path
, self
.Arch
)
2176 GlobalData
.gModuleMakeCacheStatus
[(self
.MetaFile
.Path
, self
.Arch
)] = False
2179 ModuleCacheDir
= path
.join(GlobalData
.gBinCacheSource
, self
.PlatformInfo
.OutputDir
, self
.BuildTarget
+ "_" + self
.ToolChain
, self
.Arch
, self
.SourceDir
, self
.MetaFile
.BaseName
)
2180 FfsDir
= path
.join(GlobalData
.gBinCacheSource
, self
.PlatformInfo
.OutputDir
, self
.BuildTarget
+ "_" + self
.ToolChain
, TAB_FV_DIRECTORY
, "Ffs", self
.Guid
+ self
.Name
)
2182 ModuleHashPairList
= [] # tuple list: [tuple(PreMakefileHash, MakeHash)]
2183 ModuleHashPair
= path
.join(ModuleCacheDir
, self
.Name
+ ".ModuleHashPair")
2185 with
open(LongFilePath(ModuleHashPair
), 'r') as f
:
2186 ModuleHashPairList
= json
.load(f
)
2188 # ModuleHashPair might not exist for new added module
2189 GlobalData
.gModuleMakeCacheStatus
[(self
.MetaFile
.Path
, self
.Arch
)] = False
2190 EdkLogger
.quiet("[cache warning]: fail to load ModuleHashPair file: %s" % ModuleHashPair
)
2191 print("[cache miss]: MakeCache:", self
.MetaFile
.Path
, self
.Arch
)
2194 # Check the PreMakeHash in ModuleHashPairList one by one
2195 for idx
, (PreMakefileHash
, MakeHash
) in enumerate (ModuleHashPairList
):
2196 SourceHashDir
= path
.join(ModuleCacheDir
, MakeHash
)
2197 SourceFfsHashDir
= path
.join(FfsDir
, MakeHash
)
2198 PreMakeHashFileList_FilePah
= path
.join(ModuleCacheDir
, self
.Name
+ ".PreMakeHashFileList." + PreMakefileHash
)
2199 MakeHashFileList_FilePah
= path
.join(ModuleCacheDir
, self
.Name
+ ".MakeHashFileList." + MakeHash
)
2202 with
open(LongFilePath(MakeHashFileList_FilePah
), 'r') as f
:
2203 MakeHashFileList
= json
.load(f
)
2205 EdkLogger
.quiet("[cache error]: fail to load MakeHashFileList file: %s" % MakeHashFileList_FilePah
)
2209 for HashChainFile
in MakeHashFileList
:
2210 HashChainStatus
= None
2211 if HashChainFile
in GlobalData
.gHashChainStatus
:
2212 HashChainStatus
= GlobalData
.gHashChainStatus
[HashChainFile
]
2213 if HashChainStatus
== False:
2216 elif HashChainStatus
== True:
2218 # Convert to path start with cache source dir
2219 RelativePath
= os
.path
.relpath(HashChainFile
, self
.WorkspaceDir
)
2220 NewFilePath
= os
.path
.join(GlobalData
.gBinCacheSource
, RelativePath
)
2221 if self
.CheckHashChainFile(NewFilePath
):
2222 GlobalData
.gHashChainStatus
[HashChainFile
] = True
2223 # Save the module self HashFile for GenPreMakefileHashList later usage
2224 if self
.Name
+ ".hashchain." in HashChainFile
:
2225 GlobalData
.gModuleHashFile
[(self
.MetaFile
.Path
, self
.Arch
)] = HashChainFile
2227 GlobalData
.gHashChainStatus
[HashChainFile
] = False
2234 # PreMakefile cache hit, restore the module build result
2235 for root
, dir, files
in os
.walk(SourceHashDir
):
2237 File
= path
.join(root
, f
)
2238 self
.CacheCopyFile(self
.BuildDir
, SourceHashDir
, File
)
2239 if os
.path
.exists(SourceFfsHashDir
):
2240 for root
, dir, files
in os
.walk(SourceFfsHashDir
):
2242 File
= path
.join(root
, f
)
2243 self
.CacheCopyFile(self
.FfsOutputDir
, SourceFfsHashDir
, File
)
2245 if self
.Name
== "PcdPeim" or self
.Name
== "PcdDxe":
2246 CreatePcdDatabaseCode(self
, TemplateString(), TemplateString())
2248 print("[cache hit]: MakeCache:", self
.MetaFile
.Path
, self
.Arch
)
2249 GlobalData
.gModuleMakeCacheStatus
[(self
.MetaFile
.Path
, self
.Arch
)] = True
2252 print("[cache miss]: MakeCache:", self
.MetaFile
.Path
, self
.Arch
)
2253 GlobalData
.gModuleMakeCacheStatus
[(self
.MetaFile
.Path
, self
.Arch
)] = False
2256 ## Decide whether we can skip the left autogen and make process
2257 def CanSkipbyPreMakeCache(self
):
2258 # CanSkipbyPreMakeCache consume below dicts:
2259 # gModulePreMakeCacheStatus
2262 # GenPreMakefileHashList produce gModulePreMakeCacheStatus dict.
2263 # all these dicts might be produced in multiprocessing, so
2264 # need check these remote dicts
2266 if not GlobalData
.gUseHashCache
or GlobalData
.gBinCacheDest
:
2269 if (self
.MetaFile
.Path
, self
.Arch
) in GlobalData
.gModulePreMakeCacheStatus
:
2270 return GlobalData
.gModulePreMakeCacheStatus
[(self
.MetaFile
.Path
, self
.Arch
)]
2272 # If Module is binary, which has special build rule, do not skip by cache.
2273 if self
.IsBinaryModule
:
2274 print("[cache miss]: PreMakeCache: Skip BinaryModule:", self
.MetaFile
.Path
, self
.Arch
)
2275 GlobalData
.gModulePreMakeCacheStatus
[(self
.MetaFile
.Path
, self
.Arch
)] = False
2278 # see .inc as binary file, do not skip by hash
2279 for f_ext
in self
.SourceFileList
:
2280 if '.inc' in str(f_ext
):
2281 print("[cache miss]: PreMakeCache: Skip '.inc' File:", self
.MetaFile
.Path
, self
.Arch
)
2282 GlobalData
.gModulePreMakeCacheStatus
[(self
.MetaFile
.Path
, self
.Arch
)] = False
2285 # For --hash only in the incremental build
2286 if not GlobalData
.gBinCacheSource
:
2287 Files
= [path
.join(self
.BuildDir
, f
) for f
in os
.listdir(self
.BuildDir
) if path
.isfile(path
.join(self
.BuildDir
, f
))]
2288 PreMakeHashFileList_FilePah
= None
2290 # Find latest PreMakeHashFileList file in self.BuildDir folder
2292 if ".PreMakeHashFileList." in File
:
2293 FileTimeStamp
= os
.stat(path
.join(self
.BuildDir
, File
))[8]
2294 if FileTimeStamp
> MakeTimeStamp
:
2295 MakeTimeStamp
= FileTimeStamp
2296 PreMakeHashFileList_FilePah
= File
2297 if not PreMakeHashFileList_FilePah
:
2298 GlobalData
.gModulePreMakeCacheStatus
[(self
.MetaFile
.Path
, self
.Arch
)] = False
2302 with
open(LongFilePath(PreMakeHashFileList_FilePah
), 'r') as f
:
2303 PreMakeHashFileList
= json
.load(f
)
2305 EdkLogger
.quiet("[cache error]: fail to load PreMakeHashFileList file: %s" % PreMakeHashFileList_FilePah
)
2306 print("[cache miss]: PreMakeCache:", self
.MetaFile
.Path
, self
.Arch
)
2307 GlobalData
.gModulePreMakeCacheStatus
[(self
.MetaFile
.Path
, self
.Arch
)] = False
2311 for HashChainFile
in PreMakeHashFileList
:
2312 HashChainStatus
= None
2313 if HashChainFile
in GlobalData
.gHashChainStatus
:
2314 HashChainStatus
= GlobalData
.gHashChainStatus
[HashChainFile
]
2315 if HashChainStatus
== False:
2318 elif HashChainStatus
== True:
2320 if self
.CheckHashChainFile(HashChainFile
):
2321 GlobalData
.gHashChainStatus
[HashChainFile
] = True
2322 # Save the module self HashFile for GenPreMakefileHashList later usage
2323 if self
.Name
+ ".hashchain." in HashChainFile
:
2324 GlobalData
.gModuleHashFile
[(self
.MetaFile
.Path
, self
.Arch
)] = HashChainFile
2326 GlobalData
.gHashChainStatus
[HashChainFile
] = False
2331 print("[cache miss]: PreMakeCache:", self
.MetaFile
.Path
, self
.Arch
)
2332 GlobalData
.gModulePreMakeCacheStatus
[(self
.MetaFile
.Path
, self
.Arch
)] = False
2335 print("[cache hit]: PreMakeCache:", self
.MetaFile
.Path
, self
.Arch
)
2336 GlobalData
.gModulePreMakeCacheStatus
[(self
.MetaFile
.Path
, self
.Arch
)] = True
2339 ModuleCacheDir
= path
.join(GlobalData
.gBinCacheSource
, self
.PlatformInfo
.OutputDir
, self
.BuildTarget
+ "_" + self
.ToolChain
, self
.Arch
, self
.SourceDir
, self
.MetaFile
.BaseName
)
2340 FfsDir
= path
.join(GlobalData
.gBinCacheSource
, self
.PlatformInfo
.OutputDir
, self
.BuildTarget
+ "_" + self
.ToolChain
, TAB_FV_DIRECTORY
, "Ffs", self
.Guid
+ self
.Name
)
2342 ModuleHashPairList
= [] # tuple list: [tuple(PreMakefileHash, MakeHash)]
2343 ModuleHashPair
= path
.join(ModuleCacheDir
, self
.Name
+ ".ModuleHashPair")
2345 with
open(LongFilePath(ModuleHashPair
), 'r') as f
:
2346 ModuleHashPairList
= json
.load(f
)
2348 # ModuleHashPair might not exist for new added module
2349 GlobalData
.gModulePreMakeCacheStatus
[(self
.MetaFile
.Path
, self
.Arch
)] = False
2350 EdkLogger
.quiet("[cache warning]: fail to load ModuleHashPair file: %s" % ModuleHashPair
)
2351 print("[cache miss]: PreMakeCache:", self
.MetaFile
.Path
, self
.Arch
)
2354 # Check the PreMakeHash in ModuleHashPairList one by one
2355 for idx
, (PreMakefileHash
, MakeHash
) in enumerate (ModuleHashPairList
):
2356 SourceHashDir
= path
.join(ModuleCacheDir
, MakeHash
)
2357 SourceFfsHashDir
= path
.join(FfsDir
, MakeHash
)
2358 PreMakeHashFileList_FilePah
= path
.join(ModuleCacheDir
, self
.Name
+ ".PreMakeHashFileList." + PreMakefileHash
)
2359 MakeHashFileList_FilePah
= path
.join(ModuleCacheDir
, self
.Name
+ ".MakeHashFileList." + MakeHash
)
2362 with
open(LongFilePath(PreMakeHashFileList_FilePah
), 'r') as f
:
2363 PreMakeHashFileList
= json
.load(f
)
2365 EdkLogger
.quiet("[cache error]: fail to load PreMakeHashFileList file: %s" % PreMakeHashFileList_FilePah
)
2369 for HashChainFile
in PreMakeHashFileList
:
2370 HashChainStatus
= None
2371 if HashChainFile
in GlobalData
.gHashChainStatus
:
2372 HashChainStatus
= GlobalData
.gHashChainStatus
[HashChainFile
]
2373 if HashChainStatus
== False:
2376 elif HashChainStatus
== True:
2378 # Convert to path start with cache source dir
2379 RelativePath
= os
.path
.relpath(HashChainFile
, self
.WorkspaceDir
)
2380 NewFilePath
= os
.path
.join(GlobalData
.gBinCacheSource
, RelativePath
)
2381 if self
.CheckHashChainFile(NewFilePath
):
2382 GlobalData
.gHashChainStatus
[HashChainFile
] = True
2384 GlobalData
.gHashChainStatus
[HashChainFile
] = False
2391 # PreMakefile cache hit, restore the module build result
2392 for root
, dir, files
in os
.walk(SourceHashDir
):
2394 File
= path
.join(root
, f
)
2395 self
.CacheCopyFile(self
.BuildDir
, SourceHashDir
, File
)
2396 if os
.path
.exists(SourceFfsHashDir
):
2397 for root
, dir, files
in os
.walk(SourceFfsHashDir
):
2399 File
= path
.join(root
, f
)
2400 self
.CacheCopyFile(self
.FfsOutputDir
, SourceFfsHashDir
, File
)
2402 if self
.Name
== "PcdPeim" or self
.Name
== "PcdDxe":
2403 CreatePcdDatabaseCode(self
, TemplateString(), TemplateString())
2405 print("[cache hit]: PreMakeCache:", self
.MetaFile
.Path
, self
.Arch
)
2406 GlobalData
.gModulePreMakeCacheStatus
[(self
.MetaFile
.Path
, self
.Arch
)] = True
2409 print("[cache miss]: PreMakeCache:", self
.MetaFile
.Path
, self
.Arch
)
2410 GlobalData
.gModulePreMakeCacheStatus
[(self
.MetaFile
.Path
, self
.Arch
)] = False
2413 ## Decide whether we can skip the Module build
2414 def CanSkipbyCache(self
, gHitSet
):
2415 # Hashing feature is off
2416 if not GlobalData
.gBinCacheSource
:
2424 ## Decide whether we can skip the ModuleAutoGen process
2425 # If any source file is newer than the module than we cannot skip
2428 # Don't skip if cache feature enabled
2429 if GlobalData
.gUseHashCache
or GlobalData
.gBinCacheDest
or GlobalData
.gBinCacheSource
:
2431 if self
.MakeFileDir
in GlobalData
.gSikpAutoGenCache
:
2433 if not os
.path
.exists(self
.TimeStampPath
):
2435 #last creation time of the module
2436 DstTimeStamp
= os
.stat(self
.TimeStampPath
)[8]
2438 SrcTimeStamp
= self
.Workspace
._SrcTimeStamp
2439 if SrcTimeStamp
> DstTimeStamp
:
2442 with
open(self
.TimeStampPath
,'r') as f
:
2444 source
= source
.rstrip('\n')
2445 if not os
.path
.exists(source
):
2447 if source
not in ModuleAutoGen
.TimeDict
:
2448 ModuleAutoGen
.TimeDict
[source
] = os
.stat(source
)[8]
2449 if ModuleAutoGen
.TimeDict
[source
] > DstTimeStamp
:
2451 GlobalData
.gSikpAutoGenCache
.add(self
.MakeFileDir
)
2455 def TimeStampPath(self
):
2456 return os
.path
.join(self
.MakeFileDir
, 'AutoGenTimeStamp')