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 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
30 ## Mapping Makefile type
31 gMakeTypeMap
= {TAB_COMPILER_MSFT
:"nmake", "GCC":"gmake"}
33 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT
34 # is the former use /I , the Latter used -I to specify include directories
36 gBuildOptIncludePatternMsft
= re
.compile(r
"(?:.*?)/I[ \t]*([^ ]*)", re
.MULTILINE | re
.DOTALL
)
37 gBuildOptIncludePatternOther
= re
.compile(r
"(?:.*?)-I[ \t]*([^ ]*)", re
.MULTILINE | re
.DOTALL
)
39 ## default file name for AutoGen
40 gAutoGenCodeFileName
= "AutoGen.c"
41 gAutoGenHeaderFileName
= "AutoGen.h"
42 gAutoGenStringFileName
= "%(module_name)sStrDefs.h"
43 gAutoGenStringFormFileName
= "%(module_name)sStrDefs.hpk"
44 gAutoGenDepexFileName
= "%(module_name)s.depex"
45 gAutoGenImageDefFileName
= "%(module_name)sImgDefs.h"
46 gAutoGenIdfFileName
= "%(module_name)sIdf.hpk"
47 gInfSpecVersion
= "0x00010017"
50 # Match name = variable
52 gEfiVarStoreNamePattern
= re
.compile("\s*name\s*=\s*(\w+)")
54 # The format of guid in efivarstore statement likes following and must be correct:
55 # guid = {0xA04A27f4, 0xDF00, 0x4D42, {0xB5, 0x52, 0x39, 0x51, 0x13, 0x02, 0x11, 0x3D}}
57 gEfiVarStoreGuidPattern
= re
.compile("\s*guid\s*=\s*({.*?{.*?}\s*})")
60 # Template string to generic AsBuilt INF
62 gAsBuiltInfHeaderString
= TemplateString("""${header_comments}
68 INF_VERSION = ${module_inf_version}
69 BASE_NAME = ${module_name}
70 FILE_GUID = ${module_guid}
71 MODULE_TYPE = ${module_module_type}${BEGIN}
72 VERSION_STRING = ${module_version_string}${END}${BEGIN}
73 PCD_IS_DRIVER = ${pcd_is_driver_string}${END}${BEGIN}
74 UEFI_SPECIFICATION_VERSION = ${module_uefi_specification_version}${END}${BEGIN}
75 PI_SPECIFICATION_VERSION = ${module_pi_specification_version}${END}${BEGIN}
76 ENTRY_POINT = ${module_entry_point}${END}${BEGIN}
77 UNLOAD_IMAGE = ${module_unload_image}${END}${BEGIN}
78 CONSTRUCTOR = ${module_constructor}${END}${BEGIN}
79 DESTRUCTOR = ${module_destructor}${END}${BEGIN}
80 SHADOW = ${module_shadow}${END}${BEGIN}
81 PCI_VENDOR_ID = ${module_pci_vendor_id}${END}${BEGIN}
82 PCI_DEVICE_ID = ${module_pci_device_id}${END}${BEGIN}
83 PCI_CLASS_CODE = ${module_pci_class_code}${END}${BEGIN}
84 PCI_REVISION = ${module_pci_revision}${END}${BEGIN}
85 BUILD_NUMBER = ${module_build_number}${END}${BEGIN}
86 SPEC = ${module_spec}${END}${BEGIN}
87 UEFI_HII_RESOURCE_SECTION = ${module_uefi_hii_resource_section}${END}${BEGIN}
88 MODULE_UNI_FILE = ${module_uni_file}${END}
90 [Packages.${module_arch}]${BEGIN}
93 [Binaries.${module_arch}]${BEGIN}
96 [PatchPcd.${module_arch}]${BEGIN}
100 [Protocols.${module_arch}]${BEGIN}
104 [Ppis.${module_arch}]${BEGIN}
108 [Guids.${module_arch}]${BEGIN}
112 [PcdEx.${module_arch}]${BEGIN}
116 [LibraryClasses.${module_arch}]
117 ## @LIB_INSTANCES${BEGIN}
118 # ${libraryclasses_item}${END}
122 ${userextension_tianocore_item}
126 [BuildOptions.${module_arch}]
128 ## ${flags_item}${END}
131 # extend lists contained in a dictionary with lists stored in another dictionary
132 # if CopyToDict is not derived from DefaultDict(list) then this may raise exception
134 def ExtendCopyDictionaryLists(CopyToDict
, CopyFromDict
):
135 for Key
in CopyFromDict
:
136 CopyToDict
[Key
].extend(CopyFromDict
[Key
])
138 # Create a directory specified by a set of path elements and return the full path
139 def _MakeDir(PathList
):
140 RetVal
= path
.join(*PathList
)
141 CreateDirectory(RetVal
)
145 # Convert string to C format array
147 def _ConvertStringToByteArray(Value
):
148 Value
= Value
.strip()
152 if not Value
.endswith('}'):
154 Value
= Value
.replace(' ', '').replace('{', '').replace('}', '')
155 ValFields
= Value
.split(',')
157 for Index
in range(len(ValFields
)):
158 ValFields
[Index
] = str(int(ValFields
[Index
], 0))
161 Value
= '{' + ','.join(ValFields
) + '}'
165 if Value
.startswith('L"'):
166 if not Value
.endswith('"'):
170 elif not Value
.startswith('"') or not Value
.endswith('"'):
173 Value
= eval(Value
) # translate escape character
175 for Index
in range(0, len(Value
)):
177 NewValue
= NewValue
+ str(ord(Value
[Index
]) % 0x10000) + ','
179 NewValue
= NewValue
+ str(ord(Value
[Index
]) % 0x100) + ','
180 Value
= NewValue
+ '0}'
183 ## ModuleAutoGen class
185 # This class encapsules the AutoGen behaviors for the build tools. In addition to
186 # the generation of AutoGen.h and AutoGen.c, it will generate *.depex file according
187 # to the [depex] section in module's inf file.
189 class ModuleAutoGen(AutoGen
):
190 # call super().__init__ then call the worker function with different parameter count
191 def __init__(self
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
192 if not hasattr(self
, "_Init"):
193 self
._InitWorker
(Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
)
196 ## Cache the timestamps of metafiles of every module in a class attribute
200 def __new__(cls
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
):
201 # check if this module is employed by active platform
202 if not PlatformInfo(Workspace
, args
[0], Target
, Toolchain
, Arch
,args
[-1]).ValidModule(MetaFile
):
203 EdkLogger
.verbose("Module [%s] for [%s] is not employed by active platform\n" \
206 return super(ModuleAutoGen
, cls
).__new
__(cls
, Workspace
, MetaFile
, Target
, Toolchain
, Arch
, *args
, **kwargs
)
208 ## Initialize ModuleAutoGen
210 # @param Workspace EdkIIWorkspaceBuild object
211 # @param ModuleFile The path of module file
212 # @param Target Build target (DEBUG, RELEASE)
213 # @param Toolchain Name of tool chain
214 # @param Arch The arch the module supports
215 # @param PlatformFile Platform meta-file
217 def _InitWorker(self
, Workspace
, ModuleFile
, Target
, Toolchain
, Arch
, PlatformFile
,DataPipe
):
218 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "AutoGen module [%s] [%s]" % (ModuleFile
, Arch
))
219 GlobalData
.gProcessingFile
= "%s [%s, %s, %s]" % (ModuleFile
, Arch
, Toolchain
, Target
)
221 self
.Workspace
= None
222 self
.WorkspaceDir
= ""
223 self
.PlatformInfo
= None
224 self
.DataPipe
= DataPipe
225 self
.__init
_platform
_info
__()
226 self
.MetaFile
= ModuleFile
227 self
.SourceDir
= self
.MetaFile
.SubDir
228 self
.SourceDir
= mws
.relpath(self
.SourceDir
, self
.WorkspaceDir
)
230 self
.ToolChain
= Toolchain
231 self
.BuildTarget
= Target
233 self
.ToolChainFamily
= self
.PlatformInfo
.ToolChainFamily
234 self
.BuildRuleFamily
= self
.PlatformInfo
.BuildRuleFamily
236 self
.IsCodeFileCreated
= False
237 self
.IsAsBuiltInfCreated
= False
238 self
.DepexGenerated
= False
240 self
.BuildDatabase
= self
.Workspace
.BuildDatabase
241 self
.BuildRuleOrder
= None
244 self
._GuidComments
= OrderedListDict()
245 self
._ProtocolComments
= OrderedListDict()
246 self
._PpiComments
= OrderedListDict()
247 self
._BuildTargets
= None
248 self
._IntroBuildTargetList
= None
249 self
._FinalBuildTargetList
= None
250 self
._FileTypes
= None
252 self
.AutoGenDepSet
= set()
253 self
.ReferenceModules
= []
256 def __init_platform_info__(self
):
257 pinfo
= self
.DataPipe
.Get("P_Info")
258 self
.Workspace
= WorkSpaceInfo(pinfo
.get("WorkspaceDir"),pinfo
.get("ActivePlatform"),pinfo
.get("Target"),pinfo
.get("ToolChain"),pinfo
.get("ArchList"))
259 self
.WorkspaceDir
= pinfo
.get("WorkspaceDir")
260 self
.PlatformInfo
= PlatformInfo(self
.Workspace
,pinfo
.get("ActivePlatform"),pinfo
.get("Target"),pinfo
.get("ToolChain"),pinfo
.get("Arch"),self
.DataPipe
)
261 ## hash() operator of ModuleAutoGen
263 # The module file path and arch string will be used to represent
264 # hash value of this object
266 # @retval int Hash value of the module file path and arch
268 @cached_class_function
270 return hash((self
.MetaFile
, self
.Arch
))
272 return "%s [%s]" % (self
.MetaFile
, self
.Arch
)
274 # Get FixedAtBuild Pcds of this Module
276 def FixedAtBuildPcds(self
):
278 for Pcd
in self
.ModulePcdList
:
279 if Pcd
.Type
!= TAB_PCDS_FIXED_AT_BUILD
:
281 if Pcd
not in RetVal
:
286 def FixedVoidTypePcds(self
):
288 for Pcd
in self
.FixedAtBuildPcds
:
289 if Pcd
.DatumType
== TAB_VOID
:
290 if '.'.join((Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
)) not in RetVal
:
291 RetVal
['.'.join((Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
))] = Pcd
.DefaultValue
295 def UniqueBaseName(self
):
296 ModuleNames
= self
.DataPipe
.Get("M_Name")
299 return ModuleNames
.get(self
.Name
,self
.Name
)
301 # Macros could be used in build_rule.txt (also Makefile)
305 ("WORKSPACE" ,self
.WorkspaceDir
),
306 ("MODULE_NAME" ,self
.Name
),
307 ("MODULE_NAME_GUID" ,self
.UniqueBaseName
),
308 ("MODULE_GUID" ,self
.Guid
),
309 ("MODULE_VERSION" ,self
.Version
),
310 ("MODULE_TYPE" ,self
.ModuleType
),
311 ("MODULE_FILE" ,str(self
.MetaFile
)),
312 ("MODULE_FILE_BASE_NAME" ,self
.MetaFile
.BaseName
),
313 ("MODULE_RELATIVE_DIR" ,self
.SourceDir
),
314 ("MODULE_DIR" ,self
.SourceDir
),
315 ("BASE_NAME" ,self
.Name
),
317 ("TOOLCHAIN" ,self
.ToolChain
),
318 ("TOOLCHAIN_TAG" ,self
.ToolChain
),
319 ("TOOL_CHAIN_TAG" ,self
.ToolChain
),
320 ("TARGET" ,self
.BuildTarget
),
321 ("BUILD_DIR" ,self
.PlatformInfo
.BuildDir
),
322 ("BIN_DIR" ,os
.path
.join(self
.PlatformInfo
.BuildDir
, self
.Arch
)),
323 ("LIB_DIR" ,os
.path
.join(self
.PlatformInfo
.BuildDir
, self
.Arch
)),
324 ("MODULE_BUILD_DIR" ,self
.BuildDir
),
325 ("OUTPUT_DIR" ,self
.OutputDir
),
326 ("DEBUG_DIR" ,self
.DebugDir
),
327 ("DEST_DIR_OUTPUT" ,self
.OutputDir
),
328 ("DEST_DIR_DEBUG" ,self
.DebugDir
),
329 ("PLATFORM_NAME" ,self
.PlatformInfo
.Name
),
330 ("PLATFORM_GUID" ,self
.PlatformInfo
.Guid
),
331 ("PLATFORM_VERSION" ,self
.PlatformInfo
.Version
),
332 ("PLATFORM_RELATIVE_DIR" ,self
.PlatformInfo
.SourceDir
),
333 ("PLATFORM_DIR" ,mws
.join(self
.WorkspaceDir
, self
.PlatformInfo
.SourceDir
)),
334 ("PLATFORM_OUTPUT_DIR" ,self
.PlatformInfo
.OutputDir
),
335 ("FFS_OUTPUT_DIR" ,self
.FfsOutputDir
)
338 ## Return the module build data object
341 return self
.BuildDatabase
[self
.MetaFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
343 ## Return the module name
346 return self
.Module
.BaseName
348 ## Return the module DxsFile if exist
351 return self
.Module
.DxsFile
353 ## Return the module meta-file GUID
357 # To build same module more than once, the module path with FILE_GUID overridden has
358 # the file name FILE_GUIDmodule.inf, but the relative path (self.MetaFile.File) is the real path
359 # in DSC. The overridden GUID can be retrieved from file name
361 if os
.path
.basename(self
.MetaFile
.File
) != os
.path
.basename(self
.MetaFile
.Path
):
363 # Length of GUID is 36
365 return os
.path
.basename(self
.MetaFile
.Path
)[:36]
366 return self
.Module
.Guid
368 ## Return the module version
371 return self
.Module
.Version
373 ## Return the module type
375 def ModuleType(self
):
376 return self
.Module
.ModuleType
378 ## Return the component type (for Edk.x style of module)
380 def ComponentType(self
):
381 return self
.Module
.ComponentType
383 ## Return the build type
386 return self
.Module
.BuildType
388 ## Return the PCD_IS_DRIVER setting
390 def PcdIsDriver(self
):
391 return self
.Module
.PcdIsDriver
393 ## Return the autogen version, i.e. module meta-file version
395 def AutoGenVersion(self
):
396 return self
.Module
.AutoGenVersion
398 ## Check if the module is library or not
401 return bool(self
.Module
.LibraryClass
)
403 ## Check if the module is binary module or not
405 def IsBinaryModule(self
):
406 return self
.Module
.IsBinaryModule
408 ## Return the directory to store intermediate files of the module
412 self
.PlatformInfo
.BuildDir
,
415 self
.MetaFile
.BaseName
418 ## Return the directory to store the intermediate object files of the module
421 return _MakeDir((self
.BuildDir
, "OUTPUT"))
423 ## Return the directory path to store ffs file
425 def FfsOutputDir(self
):
426 if GlobalData
.gFdfParser
:
427 return path
.join(self
.PlatformInfo
.BuildDir
, TAB_FV_DIRECTORY
, "Ffs", self
.Guid
+ self
.Name
)
430 ## Return the directory to store auto-gened source files of the module
433 return _MakeDir((self
.BuildDir
, "DEBUG"))
435 ## Return the path of custom file
437 def CustomMakefile(self
):
439 for Type
in self
.Module
.CustomMakefile
:
440 MakeType
= gMakeTypeMap
[Type
] if Type
in gMakeTypeMap
else 'nmake'
441 File
= os
.path
.join(self
.SourceDir
, self
.Module
.CustomMakefile
[Type
])
442 RetVal
[MakeType
] = File
445 ## Return the directory of the makefile
447 # @retval string The directory string of module's makefile
450 def MakeFileDir(self
):
453 ## Return build command string
455 # @retval string Build command string
458 def BuildCommand(self
):
459 return self
.PlatformInfo
.BuildCommand
461 ## Get object list of all packages the module and its dependent libraries belong to
463 # @retval list The list of package object
466 def DerivedPackageList(self
):
468 for M
in [self
.Module
] + self
.DependentLibraryList
:
469 for Package
in M
.Packages
:
470 if Package
in PackageList
:
472 PackageList
.append(Package
)
475 ## Get the depex string
477 # @return : a string contain all depex expression.
478 def _GetDepexExpresionString(self
):
481 ## DPX_SOURCE IN Define section.
482 if self
.Module
.DxsFile
:
484 for M
in [self
.Module
] + self
.DependentLibraryList
:
485 Filename
= M
.MetaFile
.Path
486 InfObj
= InfSectionParser
.InfSectionParser(Filename
)
487 DepexExpressionList
= InfObj
.GetDepexExpresionList()
488 for DepexExpression
in DepexExpressionList
:
489 for key
in DepexExpression
:
490 Arch
, ModuleType
= key
491 DepexExpr
= [x
for x
in DepexExpression
[key
] if not str(x
).startswith('#')]
492 # the type of build module is USER_DEFINED.
493 # All different DEPEX section tags would be copied into the As Built INF file
494 # and there would be separate DEPEX section tags
495 if self
.ModuleType
.upper() == SUP_MODULE_USER_DEFINED
or self
.ModuleType
.upper() == SUP_MODULE_HOST_APPLICATION
:
496 if (Arch
.upper() == self
.Arch
.upper()) and (ModuleType
.upper() != TAB_ARCH_COMMON
):
497 DepexList
.append({(Arch
, ModuleType
): DepexExpr
})
499 if Arch
.upper() == TAB_ARCH_COMMON
or \
500 (Arch
.upper() == self
.Arch
.upper() and \
501 ModuleType
.upper() in [TAB_ARCH_COMMON
, self
.ModuleType
.upper()]):
502 DepexList
.append({(Arch
, ModuleType
): DepexExpr
})
504 #the type of build module is USER_DEFINED.
505 if self
.ModuleType
.upper() == SUP_MODULE_USER_DEFINED
or self
.ModuleType
.upper() == SUP_MODULE_HOST_APPLICATION
:
506 for Depex
in DepexList
:
508 DepexStr
+= '[Depex.%s.%s]\n' % key
509 DepexStr
+= '\n'.join('# '+ val
for val
in Depex
[key
])
512 return '[Depex.%s]\n' % self
.Arch
515 #the type of build module not is USER_DEFINED.
517 for Depex
in DepexList
:
522 for D
in Depex
.values():
523 DepexStr
+= ' '.join(val
for val
in D
)
524 Index
= DepexStr
.find('END')
525 if Index
> -1 and Index
== len(DepexStr
) - 3:
526 DepexStr
= DepexStr
[:-3]
527 DepexStr
= DepexStr
.strip()
530 DepexStr
= DepexStr
.lstrip('(').rstrip(')').strip()
532 return '[Depex.%s]\n' % self
.Arch
533 return '[Depex.%s]\n# ' % self
.Arch
+ DepexStr
535 ## Merge dependency expression
537 # @retval list The token list of the dependency expression after parsed
541 if self
.DxsFile
or self
.IsLibrary
or TAB_DEPENDENCY_EXPRESSION_FILE
in self
.FileTypes
:
546 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expression
548 FixedVoidTypePcds
= {}
549 for M
in [self
] + self
.LibraryAutoGenList
:
550 FixedVoidTypePcds
.update(M
.FixedVoidTypePcds
)
551 for M
in [self
] + self
.LibraryAutoGenList
:
553 for D
in M
.Module
.Depex
[self
.Arch
, self
.ModuleType
]:
555 DepexList
.append('AND')
556 DepexList
.append('(')
557 #replace D with value if D is FixedAtBuild PCD
564 Value
= FixedVoidTypePcds
[item
]
565 if len(Value
.split(',')) != 16:
566 EdkLogger
.error("build", FORMAT_INVALID
,
567 "{} used in [Depex] section should be used as FixedAtBuild type and VOID* datum type and 16 bytes in the module.".format(item
))
568 NewList
.append(Value
)
570 EdkLogger
.error("build", FORMAT_INVALID
, "{} used in [Depex] section should be used as FixedAtBuild type and VOID* datum type in the module.".format(item
))
572 DepexList
.extend(NewList
)
573 if DepexList
[-1] == 'END': # no need of a END at this time
575 DepexList
.append(')')
578 EdkLogger
.verbose("DEPEX[%s] (+%s) = %s" % (self
.Name
, M
.Module
.BaseName
, DepexList
))
579 if 'BEFORE' in DepexList
or 'AFTER' in DepexList
:
581 if len(DepexList
) > 0:
582 EdkLogger
.verbose('')
583 return {self
.ModuleType
:DepexList
}
585 ## Merge dependency expression
587 # @retval list The token list of the dependency expression after parsed
590 def DepexExpressionDict(self
):
591 if self
.DxsFile
or self
.IsLibrary
or TAB_DEPENDENCY_EXPRESSION_FILE
in self
.FileTypes
:
594 DepexExpressionString
= ''
596 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion
598 for M
in [self
.Module
] + self
.DependentLibraryList
:
600 for D
in M
.DepexExpression
[self
.Arch
, self
.ModuleType
]:
601 if DepexExpressionString
!= '':
602 DepexExpressionString
+= ' AND '
603 DepexExpressionString
+= '('
604 DepexExpressionString
+= D
605 DepexExpressionString
= DepexExpressionString
.rstrip('END').strip()
606 DepexExpressionString
+= ')'
609 EdkLogger
.verbose("DEPEX[%s] (+%s) = %s" % (self
.Name
, M
.BaseName
, DepexExpressionString
))
610 if 'BEFORE' in DepexExpressionString
or 'AFTER' in DepexExpressionString
:
612 if len(DepexExpressionString
) > 0:
613 EdkLogger
.verbose('')
615 return {self
.ModuleType
:DepexExpressionString
}
617 # Get the tiano core user extension, it is contain dependent library.
618 # @retval: a list contain tiano core userextension.
620 def _GetTianoCoreUserExtensionList(self
):
621 TianoCoreUserExtentionList
= []
622 for M
in [self
.Module
] + self
.DependentLibraryList
:
623 Filename
= M
.MetaFile
.Path
624 InfObj
= InfSectionParser
.InfSectionParser(Filename
)
625 TianoCoreUserExtenList
= InfObj
.GetUserExtensionTianoCore()
626 for TianoCoreUserExtent
in TianoCoreUserExtenList
:
627 for Section
in TianoCoreUserExtent
:
628 ItemList
= Section
.split(TAB_SPLIT
)
630 if len(ItemList
) == 4:
632 if Arch
.upper() == TAB_ARCH_COMMON
or Arch
.upper() == self
.Arch
.upper():
634 TianoCoreList
.extend([TAB_SECTION_START
+ Section
+ TAB_SECTION_END
])
635 TianoCoreList
.extend(TianoCoreUserExtent
[Section
][:])
636 TianoCoreList
.append('\n')
637 TianoCoreUserExtentionList
.append(TianoCoreList
)
639 return TianoCoreUserExtentionList
641 ## Return the list of specification version required for the module
643 # @retval list The list of specification defined in module file
646 def Specification(self
):
647 return self
.Module
.Specification
649 ## Tool option for the module build
651 # @param PlatformInfo The object of PlatformBuildInfo
652 # @retval dict The dict containing valid options
655 def BuildOption(self
):
656 RetVal
, self
.BuildRuleOrder
= self
.PlatformInfo
.ApplyBuildOption(self
.Module
)
657 if self
.BuildRuleOrder
:
658 self
.BuildRuleOrder
= ['.%s' % Ext
for Ext
in self
.BuildRuleOrder
.split()]
661 ## Get include path list from tool option for the module build
663 # @retval list The include path list
666 def BuildOptionIncPathList(self
):
668 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT
669 # is the former use /I , the Latter used -I to specify include directories
671 if self
.PlatformInfo
.ToolChainFamily
in (TAB_COMPILER_MSFT
):
672 BuildOptIncludeRegEx
= gBuildOptIncludePatternMsft
673 elif self
.PlatformInfo
.ToolChainFamily
in ('INTEL', 'GCC', 'RVCT'):
674 BuildOptIncludeRegEx
= gBuildOptIncludePatternOther
677 # New ToolChainFamily, don't known whether there is option to specify include directories
682 for Tool
in ('CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'ASM'):
684 FlagOption
= self
.BuildOption
[Tool
]['FLAGS']
688 if self
.ToolChainFamily
!= 'RVCT':
689 IncPathList
= [NormPath(Path
, self
.Macros
) for Path
in BuildOptIncludeRegEx
.findall(FlagOption
)]
692 # RVCT may specify a list of directory seperated by commas
695 for Path
in BuildOptIncludeRegEx
.findall(FlagOption
):
696 PathList
= GetSplitList(Path
, TAB_COMMA_SPLIT
)
697 IncPathList
.extend(NormPath(PathEntry
, self
.Macros
) for PathEntry
in PathList
)
700 # EDK II modules must not reference header files outside of the packages they depend on or
701 # within the module's directory tree. Report error if violation.
703 if GlobalData
.gDisableIncludePathCheck
== False:
704 for Path
in IncPathList
:
705 if (Path
not in self
.IncludePathList
) and (CommonPath([Path
, self
.MetaFile
.Dir
]) != self
.MetaFile
.Dir
):
706 ErrMsg
= "The include directory for the EDK II module in this line is invalid %s specified in %s FLAGS '%s'" % (Path
, Tool
, FlagOption
)
707 EdkLogger
.error("build",
710 File
=str(self
.MetaFile
))
711 RetVal
+= IncPathList
714 ## Return a list of files which can be built from source
716 # What kind of files can be built is determined by build rules in
717 # $(CONF_DIRECTORY)/build_rule.txt and toolchain family.
720 def SourceFileList(self
):
722 ToolChainTagSet
= {"", TAB_STAR
, self
.ToolChain
}
723 ToolChainFamilySet
= {"", TAB_STAR
, self
.ToolChainFamily
, self
.BuildRuleFamily
}
724 for F
in self
.Module
.Sources
:
726 if F
.TagName
not in ToolChainTagSet
:
727 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "The toolchain [%s] for processing file [%s] is found, "
728 "but [%s] is currently used" % (F
.TagName
, str(F
), self
.ToolChain
))
730 # match tool chain family or build rule family
731 if F
.ToolChainFamily
not in ToolChainFamilySet
:
734 "The file [%s] must be built by tools of [%s], " \
735 "but current toolchain family is [%s], buildrule family is [%s]" \
736 % (str(F
), F
.ToolChainFamily
, self
.ToolChainFamily
, self
.BuildRuleFamily
))
739 # add the file path into search path list for file including
740 if F
.Dir
not in self
.IncludePathList
:
741 self
.IncludePathList
.insert(0, F
.Dir
)
744 self
._MatchBuildRuleOrder
(RetVal
)
747 self
._ApplyBuildRule
(F
, TAB_UNKNOWN_FILE
)
750 def _MatchBuildRuleOrder(self
, FileList
):
753 for SingleFile
in FileList
:
754 if self
.BuildRuleOrder
and SingleFile
.Ext
in self
.BuildRuleOrder
and SingleFile
.Ext
in self
.BuildRules
:
755 key
= SingleFile
.Path
.rsplit(SingleFile
.Ext
,1)[0]
756 if key
in Order_Dict
:
757 Order_Dict
[key
].append(SingleFile
.Ext
)
759 Order_Dict
[key
] = [SingleFile
.Ext
]
763 if len(Order_Dict
[F
]) > 1:
764 Order_Dict
[F
].sort(key
=lambda i
: self
.BuildRuleOrder
.index(i
))
765 for Ext
in Order_Dict
[F
][1:]:
766 RemoveList
.append(F
+ Ext
)
768 for item
in RemoveList
:
769 FileList
.remove(item
)
773 ## Return the list of unicode files
775 def UnicodeFileList(self
):
776 return self
.FileTypes
.get(TAB_UNICODE_FILE
,[])
778 ## Return the list of vfr files
780 def VfrFileList(self
):
781 return self
.FileTypes
.get(TAB_VFR_FILE
, [])
783 ## Return the list of Image Definition files
785 def IdfFileList(self
):
786 return self
.FileTypes
.get(TAB_IMAGE_FILE
,[])
788 ## Return a list of files which can be built from binary
790 # "Build" binary files are just to copy them to build directory.
792 # @retval list The list of files which can be built later
795 def BinaryFileList(self
):
797 for F
in self
.Module
.Binaries
:
798 if F
.Target
not in [TAB_ARCH_COMMON
, TAB_STAR
] and F
.Target
!= self
.BuildTarget
:
801 self
._ApplyBuildRule
(F
, F
.Type
, BinaryFileList
=RetVal
)
805 def BuildRules(self
):
807 BuildRuleDatabase
= self
.PlatformInfo
.BuildRule
808 for Type
in BuildRuleDatabase
.FileTypeList
:
809 #first try getting build rule by BuildRuleFamily
810 RuleObject
= BuildRuleDatabase
[Type
, self
.BuildType
, self
.Arch
, self
.BuildRuleFamily
]
812 # build type is always module type, but ...
813 if self
.ModuleType
!= self
.BuildType
:
814 RuleObject
= BuildRuleDatabase
[Type
, self
.ModuleType
, self
.Arch
, self
.BuildRuleFamily
]
815 #second try getting build rule by ToolChainFamily
817 RuleObject
= BuildRuleDatabase
[Type
, self
.BuildType
, self
.Arch
, self
.ToolChainFamily
]
819 # build type is always module type, but ...
820 if self
.ModuleType
!= self
.BuildType
:
821 RuleObject
= BuildRuleDatabase
[Type
, self
.ModuleType
, self
.Arch
, self
.ToolChainFamily
]
824 RuleObject
= RuleObject
.Instantiate(self
.Macros
)
825 RetVal
[Type
] = RuleObject
826 for Ext
in RuleObject
.SourceFileExtList
:
827 RetVal
[Ext
] = RuleObject
830 def _ApplyBuildRule(self
, File
, FileType
, BinaryFileList
=None):
831 if self
._BuildTargets
is None:
832 self
._IntroBuildTargetList
= set()
833 self
._FinalBuildTargetList
= set()
834 self
._BuildTargets
= defaultdict(set)
835 self
._FileTypes
= defaultdict(set)
837 if not BinaryFileList
:
838 BinaryFileList
= self
.BinaryFileList
840 SubDirectory
= os
.path
.join(self
.OutputDir
, File
.SubDir
)
841 if not os
.path
.exists(SubDirectory
):
842 CreateDirectory(SubDirectory
)
848 # Make sure to get build rule order value
852 while Index
< len(SourceList
):
853 Source
= SourceList
[Index
]
857 CreateDirectory(Source
.Dir
)
859 if File
.IsBinary
and File
== Source
and File
in BinaryFileList
:
860 # Skip all files that are not binary libraries
861 if not self
.IsLibrary
:
863 RuleObject
= self
.BuildRules
[TAB_DEFAULT_BINARY_FILE
]
864 elif FileType
in self
.BuildRules
:
865 RuleObject
= self
.BuildRules
[FileType
]
866 elif Source
.Ext
in self
.BuildRules
:
867 RuleObject
= self
.BuildRules
[Source
.Ext
]
869 # stop at no more rules
871 self
._FinalBuildTargetList
.add(LastTarget
)
874 FileType
= RuleObject
.SourceFileType
875 self
._FileTypes
[FileType
].add(Source
)
877 # stop at STATIC_LIBRARY for library
878 if self
.IsLibrary
and FileType
== TAB_STATIC_LIBRARY
:
880 self
._FinalBuildTargetList
.add(LastTarget
)
883 Target
= RuleObject
.Apply(Source
, self
.BuildRuleOrder
)
886 self
._FinalBuildTargetList
.add(LastTarget
)
888 elif not Target
.Outputs
:
889 # Only do build for target with outputs
890 self
._FinalBuildTargetList
.add(Target
)
892 self
._BuildTargets
[FileType
].add(Target
)
894 if not Source
.IsBinary
and Source
== File
:
895 self
._IntroBuildTargetList
.add(Target
)
897 # to avoid cyclic rule
898 if FileType
in RuleChain
:
901 RuleChain
.add(FileType
)
902 SourceList
.extend(Target
.Outputs
)
904 FileType
= TAB_UNKNOWN_FILE
908 if self
._BuildTargets
is None:
909 self
._IntroBuildTargetList
= set()
910 self
._FinalBuildTargetList
= set()
911 self
._BuildTargets
= defaultdict(set)
912 self
._FileTypes
= defaultdict(set)
914 #TRICK: call SourceFileList property to apply build rule for source files
917 #TRICK: call _GetBinaryFileList to apply build rule for binary files
920 return self
._BuildTargets
923 def IntroTargetList(self
):
925 return self
._IntroBuildTargetList
928 def CodaTargetList(self
):
930 return self
._FinalBuildTargetList
935 return self
._FileTypes
937 ## Get the list of package object the module depends on
939 # @retval list The package object list
942 def DependentPackageList(self
):
943 return self
.Module
.Packages
945 ## Return the list of auto-generated code file
947 # @retval list The list of auto-generated file
950 def AutoGenFileList(self
):
951 AutoGenUniIdf
= self
.BuildType
!= 'UEFI_HII'
952 UniStringBinBuffer
= BytesIO()
953 IdfGenBinBuffer
= BytesIO()
955 AutoGenC
= TemplateString()
956 AutoGenH
= TemplateString()
957 StringH
= TemplateString()
958 StringIdf
= TemplateString()
959 GenC
.CreateCode(self
, AutoGenC
, AutoGenH
, StringH
, AutoGenUniIdf
, UniStringBinBuffer
, StringIdf
, AutoGenUniIdf
, IdfGenBinBuffer
)
961 # AutoGen.c is generated if there are library classes in inf, or there are object files
963 if str(AutoGenC
) != "" and (len(self
.Module
.LibraryClasses
) > 0
964 or TAB_OBJECT_FILE
in self
.FileTypes
):
965 AutoFile
= PathClass(gAutoGenCodeFileName
, self
.DebugDir
)
966 RetVal
[AutoFile
] = str(AutoGenC
)
967 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
968 if str(AutoGenH
) != "":
969 AutoFile
= PathClass(gAutoGenHeaderFileName
, self
.DebugDir
)
970 RetVal
[AutoFile
] = str(AutoGenH
)
971 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
972 if str(StringH
) != "":
973 AutoFile
= PathClass(gAutoGenStringFileName
% {"module_name":self
.Name
}, self
.DebugDir
)
974 RetVal
[AutoFile
] = str(StringH
)
975 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
976 if UniStringBinBuffer
is not None and UniStringBinBuffer
.getvalue() != b
"":
977 AutoFile
= PathClass(gAutoGenStringFormFileName
% {"module_name":self
.Name
}, self
.OutputDir
)
978 RetVal
[AutoFile
] = UniStringBinBuffer
.getvalue()
979 AutoFile
.IsBinary
= True
980 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
981 if UniStringBinBuffer
is not None:
982 UniStringBinBuffer
.close()
983 if str(StringIdf
) != "":
984 AutoFile
= PathClass(gAutoGenImageDefFileName
% {"module_name":self
.Name
}, self
.DebugDir
)
985 RetVal
[AutoFile
] = str(StringIdf
)
986 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
987 if IdfGenBinBuffer
is not None and IdfGenBinBuffer
.getvalue() != b
"":
988 AutoFile
= PathClass(gAutoGenIdfFileName
% {"module_name":self
.Name
}, self
.OutputDir
)
989 RetVal
[AutoFile
] = IdfGenBinBuffer
.getvalue()
990 AutoFile
.IsBinary
= True
991 self
._ApplyBuildRule
(AutoFile
, TAB_UNKNOWN_FILE
)
992 if IdfGenBinBuffer
is not None:
993 IdfGenBinBuffer
.close()
996 ## Return the list of library modules explicitly or implicitly used by this module
998 def DependentLibraryList(self
):
999 # only merge library classes and PCD for non-library module
1002 return self
.PlatformInfo
.ApplyLibraryInstance(self
.Module
)
1004 ## Get the list of PCDs from current module
1006 # @retval list The list of PCD
1009 def ModulePcdList(self
):
1010 # apply PCD settings from platform
1011 RetVal
= self
.PlatformInfo
.ApplyPcdSetting(self
.Module
, self
.Module
.Pcds
)
1015 def _PcdComments(self
):
1016 ReVal
= OrderedListDict()
1017 ExtendCopyDictionaryLists(ReVal
, self
.Module
.PcdComments
)
1018 if not self
.IsLibrary
:
1019 for Library
in self
.DependentLibraryList
:
1020 ExtendCopyDictionaryLists(ReVal
, Library
.PcdComments
)
1023 ## Get the list of PCDs from dependent libraries
1025 # @retval list The list of PCD
1028 def LibraryPcdList(self
):
1033 # get PCDs from dependent libraries
1034 for Library
in self
.DependentLibraryList
:
1035 PcdsInLibrary
= OrderedDict()
1036 for Key
in Library
.Pcds
:
1037 # skip duplicated PCDs
1038 if Key
in self
.Module
.Pcds
or Key
in Pcds
:
1041 PcdsInLibrary
[Key
] = copy
.copy(Library
.Pcds
[Key
])
1042 RetVal
.extend(self
.PlatformInfo
.ApplyPcdSetting(self
.Module
, PcdsInLibrary
, Library
=Library
))
1045 ## Get the GUID value mapping
1047 # @retval dict The mapping between GUID cname and its value
1051 RetVal
= self
.Module
.Guids
1052 for Library
in self
.DependentLibraryList
:
1053 RetVal
.update(Library
.Guids
)
1054 ExtendCopyDictionaryLists(self
._GuidComments
, Library
.GuidComments
)
1055 ExtendCopyDictionaryLists(self
._GuidComments
, self
.Module
.GuidComments
)
1059 def GetGuidsUsedByPcd(self
):
1060 RetVal
= OrderedDict(self
.Module
.GetGuidsUsedByPcd())
1061 for Library
in self
.DependentLibraryList
:
1062 RetVal
.update(Library
.GetGuidsUsedByPcd())
1064 ## Get the protocol value mapping
1066 # @retval dict The mapping between protocol cname and its value
1069 def ProtocolList(self
):
1070 RetVal
= OrderedDict(self
.Module
.Protocols
)
1071 for Library
in self
.DependentLibraryList
:
1072 RetVal
.update(Library
.Protocols
)
1073 ExtendCopyDictionaryLists(self
._ProtocolComments
, Library
.ProtocolComments
)
1074 ExtendCopyDictionaryLists(self
._ProtocolComments
, self
.Module
.ProtocolComments
)
1077 ## Get the PPI value mapping
1079 # @retval dict The mapping between PPI cname and its value
1083 RetVal
= OrderedDict(self
.Module
.Ppis
)
1084 for Library
in self
.DependentLibraryList
:
1085 RetVal
.update(Library
.Ppis
)
1086 ExtendCopyDictionaryLists(self
._PpiComments
, Library
.PpiComments
)
1087 ExtendCopyDictionaryLists(self
._PpiComments
, self
.Module
.PpiComments
)
1090 ## Get the list of include search path
1092 # @retval list The list path
1095 def IncludePathList(self
):
1097 RetVal
.append(self
.MetaFile
.Dir
)
1098 RetVal
.append(self
.DebugDir
)
1100 for Package
in self
.Module
.Packages
:
1101 PackageDir
= mws
.join(self
.WorkspaceDir
, Package
.MetaFile
.Dir
)
1102 if PackageDir
not in RetVal
:
1103 RetVal
.append(PackageDir
)
1104 IncludesList
= Package
.Includes
1105 if Package
._PrivateIncludes
:
1106 if not self
.MetaFile
.OriginalPath
.Path
.startswith(PackageDir
):
1107 IncludesList
= list(set(Package
.Includes
).difference(set(Package
._PrivateIncludes
)))
1108 for Inc
in IncludesList
:
1109 if Inc
not in RetVal
:
1110 RetVal
.append(str(Inc
))
1114 def IncludePathLength(self
):
1115 return sum(len(inc
)+1 for inc
in self
.IncludePathList
)
1117 ## Get HII EX PCDs which maybe used by VFR
1119 # efivarstore used by VFR may relate with HII EX PCDs
1120 # Get the variable name and GUID from efivarstore and HII EX PCD
1121 # List the HII EX PCDs in As Built INF if both name and GUID match.
1123 # @retval list HII EX PCDs
1125 def _GetPcdsMaybeUsedByVfr(self
):
1126 if not self
.SourceFileList
:
1130 for SrcFile
in self
.SourceFileList
:
1131 if SrcFile
.Ext
.lower() != '.vfr':
1133 Vfri
= os
.path
.join(self
.OutputDir
, SrcFile
.BaseName
+ '.i')
1134 if not os
.path
.exists(Vfri
):
1136 VfriFile
= open(Vfri
, 'r')
1137 Content
= VfriFile
.read()
1139 Pos
= Content
.find('efivarstore')
1142 # Make sure 'efivarstore' is the start of efivarstore statement
1143 # In case of the value of 'name' (name = efivarstore) is equal to 'efivarstore'
1146 while Index
>= 0 and Content
[Index
] in ' \t\r\n':
1148 if Index
>= 0 and Content
[Index
] != ';':
1149 Pos
= Content
.find('efivarstore', Pos
+ len('efivarstore'))
1152 # 'efivarstore' must be followed by name and guid
1154 Name
= gEfiVarStoreNamePattern
.search(Content
, Pos
)
1157 Guid
= gEfiVarStoreGuidPattern
.search(Content
, Pos
)
1160 NameArray
= _ConvertStringToByteArray('L"' + Name
.group(1) + '"')
1161 NameGuids
.add((NameArray
, GuidStructureStringToGuidString(Guid
.group(1))))
1162 Pos
= Content
.find('efivarstore', Name
.end())
1166 for Pcd
in self
.PlatformInfo
.Pcds
.values():
1167 if Pcd
.Type
!= TAB_PCDS_DYNAMIC_EX_HII
:
1169 for SkuInfo
in Pcd
.SkuInfoList
.values():
1170 Value
= GuidValue(SkuInfo
.VariableGuid
, self
.PlatformInfo
.PackageList
, self
.MetaFile
.Path
)
1173 Name
= _ConvertStringToByteArray(SkuInfo
.VariableName
)
1174 Guid
= GuidStructureStringToGuidString(Value
)
1175 if (Name
, Guid
) in NameGuids
and Pcd
not in HiiExPcds
:
1176 HiiExPcds
.append(Pcd
)
1181 def _GenOffsetBin(self
):
1183 for SourceFile
in self
.Module
.Sources
:
1184 if SourceFile
.Type
.upper() == ".VFR" :
1186 # search the .map file to find the offset of vfr binary in the PE32+/TE file.
1188 VfrUniBaseName
[SourceFile
.BaseName
] = (SourceFile
.BaseName
+ "Bin")
1189 elif SourceFile
.Type
.upper() == ".UNI" :
1191 # search the .map file to find the offset of Uni strings binary in the PE32+/TE file.
1193 VfrUniBaseName
["UniOffsetName"] = (self
.Name
+ "Strings")
1195 if not VfrUniBaseName
:
1197 MapFileName
= os
.path
.join(self
.OutputDir
, self
.Name
+ ".map")
1198 EfiFileName
= os
.path
.join(self
.OutputDir
, self
.Name
+ ".efi")
1199 VfrUniOffsetList
= GetVariableOffset(MapFileName
, EfiFileName
, list(VfrUniBaseName
.values()))
1200 if not VfrUniOffsetList
:
1203 OutputName
= '%sOffset.bin' % self
.Name
1204 UniVfrOffsetFileName
= os
.path
.join( self
.OutputDir
, OutputName
)
1207 fInputfile
= open(UniVfrOffsetFileName
, "wb+", 0)
1209 EdkLogger
.error("build", FILE_OPEN_FAILURE
, "File open failed for %s" % UniVfrOffsetFileName
, None)
1211 # Use a instance of BytesIO to cache data
1212 fStringIO
= BytesIO()
1214 for Item
in VfrUniOffsetList
:
1215 if (Item
[0].find("Strings") != -1):
1217 # UNI offset in image.
1219 # { 0x8913c5e0, 0x33f6, 0x4d86, { 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66 } }
1221 UniGuid
= b
'\xe0\xc5\x13\x89\xf63\x86M\x9b\xf1C\xef\x89\xfc\x06f'
1222 fStringIO
.write(UniGuid
)
1223 UniValue
= pack ('Q', int (Item
[1], 16))
1224 fStringIO
.write (UniValue
)
1227 # VFR binary offset in image.
1229 # { 0xd0bc7cb4, 0x6a47, 0x495f, { 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2 } };
1231 VfrGuid
= b
'\xb4|\xbc\xd0Gj_I\xaa\x11q\x07F\xda\x06\xa2'
1232 fStringIO
.write(VfrGuid
)
1233 VfrValue
= pack ('Q', int (Item
[1], 16))
1234 fStringIO
.write (VfrValue
)
1236 # write data into file.
1239 fInputfile
.write (fStringIO
.getvalue())
1241 EdkLogger
.error("build", FILE_WRITE_FAILURE
, "Write data to file %s failed, please check whether the "
1242 "file been locked or using by other applications." %UniVfrOffsetFileName
, None)
1248 def OutputFile(self
):
1250 OutputDir
= self
.OutputDir
.replace('\\', '/').strip('/')
1251 DebugDir
= self
.DebugDir
.replace('\\', '/').strip('/')
1252 for Item
in self
.CodaTargetList
:
1253 File
= Item
.Target
.Path
.replace('\\', '/').strip('/').replace(DebugDir
, '').replace(OutputDir
, '').strip('/')
1255 if self
.DepexGenerated
:
1256 retVal
.add(self
.Name
+ '.depex')
1258 Bin
= self
._GenOffsetBin
()
1262 for Root
, Dirs
, Files
in os
.walk(OutputDir
):
1264 if File
.lower().endswith('.pdb'):
1269 ## Create AsBuilt INF file the module
1271 def CreateAsBuiltInf(self
):
1273 if self
.IsAsBuiltInfCreated
:
1276 # Skip INF file generation for libraries
1280 # Skip the following code for modules with no source files
1281 if not self
.SourceFileList
:
1284 # Skip the following code for modules without any binary files
1285 if self
.BinaryFileList
:
1288 ### TODO: How to handles mixed source and binary modules
1290 # Find all DynamicEx and PatchableInModule PCDs used by this module and dependent libraries
1291 # Also find all packages that the DynamicEx PCDs depend on
1296 PcdTokenSpaceList
= []
1297 for Pcd
in self
.ModulePcdList
+ self
.LibraryPcdList
:
1298 if Pcd
.Type
== TAB_PCDS_PATCHABLE_IN_MODULE
:
1299 PatchablePcds
.append(Pcd
)
1300 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, TAB_PCDS_PATCHABLE_IN_MODULE
))
1301 elif Pcd
.Type
in PCD_DYNAMIC_EX_TYPE_SET
:
1304 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC_EX
))
1305 PcdCheckList
.append((Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC
))
1306 PcdTokenSpaceList
.append(Pcd
.TokenSpaceGuidCName
)
1307 GuidList
= OrderedDict(self
.GuidList
)
1308 for TokenSpace
in self
.GetGuidsUsedByPcd
:
1309 # If token space is not referred by patch PCD or Ex PCD, remove the GUID from GUID list
1310 # The GUIDs in GUIDs section should really be the GUIDs in source INF or referred by Ex an patch PCDs
1311 if TokenSpace
not in PcdTokenSpaceList
and TokenSpace
in GuidList
:
1312 GuidList
.pop(TokenSpace
)
1313 CheckList
= (GuidList
, self
.PpiList
, self
.ProtocolList
, PcdCheckList
)
1314 for Package
in self
.DerivedPackageList
:
1315 if Package
in Packages
:
1317 BeChecked
= (Package
.Guids
, Package
.Ppis
, Package
.Protocols
, Package
.Pcds
)
1319 for Index
in range(len(BeChecked
)):
1320 for Item
in CheckList
[Index
]:
1321 if Item
in BeChecked
[Index
]:
1322 Packages
.append(Package
)
1328 VfrPcds
= self
._GetPcdsMaybeUsedByVfr
()
1329 for Pkg
in self
.PlatformInfo
.PackageList
:
1332 for VfrPcd
in VfrPcds
:
1333 if ((VfrPcd
.TokenCName
, VfrPcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC_EX
) in Pkg
.Pcds
or
1334 (VfrPcd
.TokenCName
, VfrPcd
.TokenSpaceGuidCName
, TAB_PCDS_DYNAMIC
) in Pkg
.Pcds
):
1335 Packages
.append(Pkg
)
1338 ModuleType
= SUP_MODULE_DXE_DRIVER
if self
.ModuleType
== SUP_MODULE_UEFI_DRIVER
and self
.DepexGenerated
else self
.ModuleType
1339 DriverType
= self
.PcdIsDriver
if self
.PcdIsDriver
else ''
1341 MDefs
= self
.Module
.Defines
1344 'module_name' : self
.Name
,
1345 'module_guid' : Guid
,
1346 'module_module_type' : ModuleType
,
1347 'module_version_string' : [MDefs
['VERSION_STRING']] if 'VERSION_STRING' in MDefs
else [],
1348 'pcd_is_driver_string' : [],
1349 'module_uefi_specification_version' : [],
1350 'module_pi_specification_version' : [],
1351 'module_entry_point' : self
.Module
.ModuleEntryPointList
,
1352 'module_unload_image' : self
.Module
.ModuleUnloadImageList
,
1353 'module_constructor' : self
.Module
.ConstructorList
,
1354 'module_destructor' : self
.Module
.DestructorList
,
1355 'module_shadow' : [MDefs
['SHADOW']] if 'SHADOW' in MDefs
else [],
1356 'module_pci_vendor_id' : [MDefs
['PCI_VENDOR_ID']] if 'PCI_VENDOR_ID' in MDefs
else [],
1357 'module_pci_device_id' : [MDefs
['PCI_DEVICE_ID']] if 'PCI_DEVICE_ID' in MDefs
else [],
1358 'module_pci_class_code' : [MDefs
['PCI_CLASS_CODE']] if 'PCI_CLASS_CODE' in MDefs
else [],
1359 'module_pci_revision' : [MDefs
['PCI_REVISION']] if 'PCI_REVISION' in MDefs
else [],
1360 'module_build_number' : [MDefs
['BUILD_NUMBER']] if 'BUILD_NUMBER' in MDefs
else [],
1361 'module_spec' : [MDefs
['SPEC']] if 'SPEC' in MDefs
else [],
1362 'module_uefi_hii_resource_section' : [MDefs
['UEFI_HII_RESOURCE_SECTION']] if 'UEFI_HII_RESOURCE_SECTION' in MDefs
else [],
1363 'module_uni_file' : [MDefs
['MODULE_UNI_FILE']] if 'MODULE_UNI_FILE' in MDefs
else [],
1364 'module_arch' : self
.Arch
,
1365 'package_item' : [Package
.MetaFile
.File
.replace('\\', '/') for Package
in Packages
],
1367 'patchablepcd_item' : [],
1369 'protocol_item' : [],
1373 'libraryclasses_item' : []
1376 if 'MODULE_UNI_FILE' in MDefs
:
1377 UNIFile
= os
.path
.join(self
.MetaFile
.Dir
, MDefs
['MODULE_UNI_FILE'])
1378 if os
.path
.isfile(UNIFile
):
1379 shutil
.copy2(UNIFile
, self
.OutputDir
)
1381 if self
.AutoGenVersion
> int(gInfSpecVersion
, 0):
1382 AsBuiltInfDict
['module_inf_version'] = '0x%08x' % self
.AutoGenVersion
1384 AsBuiltInfDict
['module_inf_version'] = gInfSpecVersion
1387 AsBuiltInfDict
['pcd_is_driver_string'].append(DriverType
)
1389 if 'UEFI_SPECIFICATION_VERSION' in self
.Specification
:
1390 AsBuiltInfDict
['module_uefi_specification_version'].append(self
.Specification
['UEFI_SPECIFICATION_VERSION'])
1391 if 'PI_SPECIFICATION_VERSION' in self
.Specification
:
1392 AsBuiltInfDict
['module_pi_specification_version'].append(self
.Specification
['PI_SPECIFICATION_VERSION'])
1394 OutputDir
= self
.OutputDir
.replace('\\', '/').strip('/')
1395 DebugDir
= self
.DebugDir
.replace('\\', '/').strip('/')
1396 for Item
in self
.CodaTargetList
:
1397 File
= Item
.Target
.Path
.replace('\\', '/').strip('/').replace(DebugDir
, '').replace(OutputDir
, '').strip('/')
1398 if os
.path
.isabs(File
):
1399 File
= File
.replace('\\', '/').strip('/').replace(OutputDir
, '').strip('/')
1400 if Item
.Target
.Ext
.lower() == '.aml':
1401 AsBuiltInfDict
['binary_item'].append('ASL|' + File
)
1402 elif Item
.Target
.Ext
.lower() == '.acpi':
1403 AsBuiltInfDict
['binary_item'].append('ACPI|' + File
)
1404 elif Item
.Target
.Ext
.lower() == '.efi':
1405 AsBuiltInfDict
['binary_item'].append('PE32|' + self
.Name
+ '.efi')
1407 AsBuiltInfDict
['binary_item'].append('BIN|' + File
)
1408 if not self
.DepexGenerated
:
1409 DepexFile
= os
.path
.join(self
.OutputDir
, self
.Name
+ '.depex')
1410 if os
.path
.exists(DepexFile
):
1411 self
.DepexGenerated
= True
1412 if self
.DepexGenerated
:
1413 if self
.ModuleType
in [SUP_MODULE_PEIM
]:
1414 AsBuiltInfDict
['binary_item'].append('PEI_DEPEX|' + self
.Name
+ '.depex')
1415 elif self
.ModuleType
in [SUP_MODULE_DXE_DRIVER
, SUP_MODULE_DXE_RUNTIME_DRIVER
, SUP_MODULE_DXE_SAL_DRIVER
, SUP_MODULE_UEFI_DRIVER
]:
1416 AsBuiltInfDict
['binary_item'].append('DXE_DEPEX|' + self
.Name
+ '.depex')
1417 elif self
.ModuleType
in [SUP_MODULE_DXE_SMM_DRIVER
]:
1418 AsBuiltInfDict
['binary_item'].append('SMM_DEPEX|' + self
.Name
+ '.depex')
1420 Bin
= self
._GenOffsetBin
()
1422 AsBuiltInfDict
['binary_item'].append('BIN|%s' % Bin
)
1424 for Root
, Dirs
, Files
in os
.walk(OutputDir
):
1426 if File
.lower().endswith('.pdb'):
1427 AsBuiltInfDict
['binary_item'].append('DISPOSABLE|' + File
)
1428 HeaderComments
= self
.Module
.HeaderComments
1430 for Index
in range(len(HeaderComments
)):
1431 if HeaderComments
[Index
].find('@BinaryHeader') != -1:
1432 HeaderComments
[Index
] = HeaderComments
[Index
].replace('@BinaryHeader', '@file')
1435 AsBuiltInfDict
['header_comments'] = '\n'.join(HeaderComments
[StartPos
:]).replace(':#', '://')
1436 AsBuiltInfDict
['tail_comments'] = '\n'.join(self
.Module
.TailComments
)
1439 (self
.ProtocolList
, self
._ProtocolComments
, 'protocol_item'),
1440 (self
.PpiList
, self
._PpiComments
, 'ppi_item'),
1441 (GuidList
, self
._GuidComments
, 'guid_item')
1443 for Item
in GenList
:
1444 for CName
in Item
[0]:
1445 Comments
= '\n '.join(Item
[1][CName
]) if CName
in Item
[1] else ''
1446 Entry
= Comments
+ '\n ' + CName
if Comments
else CName
1447 AsBuiltInfDict
[Item
[2]].append(Entry
)
1448 PatchList
= parsePcdInfoFromMapFile(
1449 os
.path
.join(self
.OutputDir
, self
.Name
+ '.map'),
1450 os
.path
.join(self
.OutputDir
, self
.Name
+ '.efi')
1453 for Pcd
in PatchablePcds
:
1454 TokenCName
= Pcd
.TokenCName
1455 for PcdItem
in GlobalData
.MixedPcd
:
1456 if (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
1457 TokenCName
= PcdItem
[0]
1459 for PatchPcd
in PatchList
:
1460 if TokenCName
== PatchPcd
[0]:
1465 if Pcd
.DatumType
== 'BOOLEAN':
1466 BoolValue
= Pcd
.DefaultValue
.upper()
1467 if BoolValue
== 'TRUE':
1468 Pcd
.DefaultValue
= '1'
1469 elif BoolValue
== 'FALSE':
1470 Pcd
.DefaultValue
= '0'
1472 if Pcd
.DatumType
in TAB_PCD_NUMERIC_TYPES
:
1473 HexFormat
= '0x%02x'
1474 if Pcd
.DatumType
== TAB_UINT16
:
1475 HexFormat
= '0x%04x'
1476 elif Pcd
.DatumType
== TAB_UINT32
:
1477 HexFormat
= '0x%08x'
1478 elif Pcd
.DatumType
== TAB_UINT64
:
1479 HexFormat
= '0x%016x'
1480 PcdValue
= HexFormat
% int(Pcd
.DefaultValue
, 0)
1482 if Pcd
.MaxDatumSize
is None or Pcd
.MaxDatumSize
== '':
1483 EdkLogger
.error("build", AUTOGEN_ERROR
,
1484 "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
1486 ArraySize
= int(Pcd
.MaxDatumSize
, 0)
1487 PcdValue
= Pcd
.DefaultValue
1488 if PcdValue
[0] != '{':
1490 if PcdValue
[0] == 'L':
1492 PcdValue
= PcdValue
.lstrip('L')
1493 PcdValue
= eval(PcdValue
)
1495 for Index
in range(0, len(PcdValue
)):
1497 CharVal
= ord(PcdValue
[Index
])
1498 NewValue
= NewValue
+ '0x%02x' % (CharVal
& 0x00FF) + ', ' \
1499 + '0x%02x' % (CharVal
>> 8) + ', '
1501 NewValue
= NewValue
+ '0x%02x' % (ord(PcdValue
[Index
]) % 0x100) + ', '
1504 Padding
= Padding
* 2
1505 ArraySize
= ArraySize
// 2
1506 if ArraySize
< (len(PcdValue
) + 1):
1507 if Pcd
.MaxSizeUserSet
:
1508 EdkLogger
.error("build", AUTOGEN_ERROR
,
1509 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
1512 ArraySize
= len(PcdValue
) + 1
1513 if ArraySize
> len(PcdValue
) + 1:
1514 NewValue
= NewValue
+ Padding
* (ArraySize
- len(PcdValue
) - 1)
1515 PcdValue
= NewValue
+ Padding
.strip().rstrip(',') + '}'
1516 elif len(PcdValue
.split(',')) <= ArraySize
:
1517 PcdValue
= PcdValue
.rstrip('}') + ', 0x00' * (ArraySize
- len(PcdValue
.split(',')))
1520 if Pcd
.MaxSizeUserSet
:
1521 EdkLogger
.error("build", AUTOGEN_ERROR
,
1522 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd
.TokenSpaceGuidCName
, TokenCName
)
1525 ArraySize
= len(PcdValue
) + 1
1526 PcdItem
= '%s.%s|%s|0x%X' % \
1527 (Pcd
.TokenSpaceGuidCName
, TokenCName
, PcdValue
, PatchPcd
[1])
1529 if (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) in self
._PcdComments
:
1530 PcdComments
= '\n '.join(self
._PcdComments
[Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
])
1532 PcdItem
= PcdComments
+ '\n ' + PcdItem
1533 AsBuiltInfDict
['patchablepcd_item'].append(PcdItem
)
1535 for Pcd
in Pcds
+ VfrPcds
:
1538 TokenCName
= Pcd
.TokenCName
1539 for PcdItem
in GlobalData
.MixedPcd
:
1540 if (Pcd
.TokenCName
, Pcd
.TokenSpaceGuidCName
) in GlobalData
.MixedPcd
[PcdItem
]:
1541 TokenCName
= PcdItem
[0]
1543 if Pcd
.Type
== TAB_PCDS_DYNAMIC_EX_HII
:
1544 for SkuName
in Pcd
.SkuInfoList
:
1545 SkuInfo
= Pcd
.SkuInfoList
[SkuName
]
1546 HiiInfo
= '## %s|%s|%s' % (SkuInfo
.VariableName
, SkuInfo
.VariableGuid
, SkuInfo
.VariableOffset
)
1548 if (Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
) in self
._PcdComments
:
1549 PcdCommentList
= self
._PcdComments
[Pcd
.TokenSpaceGuidCName
, Pcd
.TokenCName
][:]
1553 for Index
, Comment
in enumerate(PcdCommentList
):
1554 for Usage
in UsageList
:
1555 if Comment
.find(Usage
) != -1:
1559 if UsageIndex
!= -1:
1560 PcdCommentList
[UsageIndex
] = '## %s %s %s' % (UsageStr
, HiiInfo
, PcdCommentList
[UsageIndex
].replace(UsageStr
, ''))
1562 PcdCommentList
.append('## UNDEFINED ' + HiiInfo
)
1563 PcdComments
= '\n '.join(PcdCommentList
)
1564 PcdEntry
= Pcd
.TokenSpaceGuidCName
+ '.' + TokenCName
1566 PcdEntry
= PcdComments
+ '\n ' + PcdEntry
1567 AsBuiltInfDict
['pcd_item'].append(PcdEntry
)
1568 for Item
in self
.BuildOption
:
1569 if 'FLAGS' in self
.BuildOption
[Item
]:
1570 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()))
1572 # Generated LibraryClasses section in comments.
1573 for Library
in self
.LibraryAutoGenList
:
1574 AsBuiltInfDict
['libraryclasses_item'].append(Library
.MetaFile
.File
.replace('\\', '/'))
1576 # Generated UserExtensions TianoCore section.
1577 # All tianocore user extensions are copied.
1579 for TianoCore
in self
._GetTianoCoreUserExtensionList
():
1580 UserExtStr
+= '\n'.join(TianoCore
)
1581 ExtensionFile
= os
.path
.join(self
.MetaFile
.Dir
, TianoCore
[1])
1582 if os
.path
.isfile(ExtensionFile
):
1583 shutil
.copy2(ExtensionFile
, self
.OutputDir
)
1584 AsBuiltInfDict
['userextension_tianocore_item'] = UserExtStr
1586 # Generated depex expression section in comments.
1587 DepexExpression
= self
._GetDepexExpresionString
()
1588 AsBuiltInfDict
['depexsection_item'] = DepexExpression
if DepexExpression
else ''
1590 AsBuiltInf
= TemplateString()
1591 AsBuiltInf
.Append(gAsBuiltInfHeaderString
.Replace(AsBuiltInfDict
))
1593 SaveFileOnChange(os
.path
.join(self
.OutputDir
, self
.Name
+ '.inf'), str(AsBuiltInf
), False)
1595 self
.IsAsBuiltInfCreated
= True
1597 def CopyModuleToCache(self
):
1598 FileDir
= path
.join(GlobalData
.gBinCacheDest
, self
.PlatformInfo
.Name
, self
.BuildTarget
+ "_" + self
.ToolChain
, self
.Arch
, self
.SourceDir
, self
.MetaFile
.BaseName
)
1599 CreateDirectory (FileDir
)
1600 HashFile
= path
.join(self
.BuildDir
, self
.Name
+ '.hash')
1601 if os
.path
.exists(HashFile
):
1602 CopyFileOnChange(HashFile
, FileDir
)
1603 ModuleFile
= path
.join(self
.OutputDir
, self
.Name
+ '.inf')
1604 if os
.path
.exists(ModuleFile
):
1605 CopyFileOnChange(ModuleFile
, FileDir
)
1606 if not self
.OutputFile
:
1607 Ma
= self
.BuildDatabase
[self
.MetaFile
, self
.Arch
, self
.BuildTarget
, self
.ToolChain
]
1608 self
.OutputFile
= Ma
.Binaries
1609 for File
in self
.OutputFile
:
1611 if not os
.path
.isabs(File
):
1612 File
= os
.path
.join(self
.OutputDir
, File
)
1613 if os
.path
.exists(File
):
1614 sub_dir
= os
.path
.relpath(File
, self
.OutputDir
)
1615 destination_file
= os
.path
.join(FileDir
, sub_dir
)
1616 destination_dir
= os
.path
.dirname(destination_file
)
1617 CreateDirectory(destination_dir
)
1618 CopyFileOnChange(File
, destination_dir
)
1620 def AttemptModuleCacheCopy(self
):
1621 # If library or Module is binary do not skip by hash
1622 if self
.IsBinaryModule
:
1624 # .inc is contains binary information so do not skip by hash as well
1625 for f_ext
in self
.SourceFileList
:
1626 if '.inc' in str(f_ext
):
1628 FileDir
= path
.join(GlobalData
.gBinCacheSource
, self
.PlatformInfo
.Name
, self
.BuildTarget
+ "_" + self
.ToolChain
, self
.Arch
, self
.SourceDir
, self
.MetaFile
.BaseName
)
1629 HashFile
= path
.join(FileDir
, self
.Name
+ '.hash')
1630 if os
.path
.exists(HashFile
):
1631 f
= open(HashFile
, 'r')
1632 CacheHash
= f
.read()
1634 self
.GenModuleHash()
1635 if GlobalData
.gModuleHash
[self
.Arch
][self
.Name
]:
1636 if CacheHash
== GlobalData
.gModuleHash
[self
.Arch
][self
.Name
]:
1637 for root
, dir, files
in os
.walk(FileDir
):
1639 if self
.Name
+ '.hash' in f
:
1640 CopyFileOnChange(HashFile
, self
.BuildDir
)
1642 File
= path
.join(root
, f
)
1643 sub_dir
= os
.path
.relpath(File
, FileDir
)
1644 destination_file
= os
.path
.join(self
.OutputDir
, sub_dir
)
1645 destination_dir
= os
.path
.dirname(destination_file
)
1646 CreateDirectory(destination_dir
)
1647 CopyFileOnChange(File
, destination_dir
)
1648 if self
.Name
== "PcdPeim" or self
.Name
== "PcdDxe":
1649 CreatePcdDatabaseCode(self
, TemplateString(), TemplateString())
1653 ## Create makefile for the module and its dependent libraries
1655 # @param CreateLibraryMakeFile Flag indicating if or not the makefiles of
1656 # dependent libraries will be created
1658 @cached_class_function
1659 def CreateMakeFile(self
, CreateLibraryMakeFile
=True, GenFfsList
= []):
1660 # nest this function inside it's only caller.
1661 def CreateTimeStamp():
1662 FileSet
= {self
.MetaFile
.Path
}
1664 for SourceFile
in self
.Module
.Sources
:
1665 FileSet
.add (SourceFile
.Path
)
1667 for Lib
in self
.DependentLibraryList
:
1668 FileSet
.add (Lib
.MetaFile
.Path
)
1670 for f
in self
.AutoGenDepSet
:
1671 FileSet
.add (f
.Path
)
1673 if os
.path
.exists (self
.TimeStampPath
):
1674 os
.remove (self
.TimeStampPath
)
1675 with
open(self
.TimeStampPath
, 'w+') as fd
:
1680 # Ignore generating makefile when it is a binary module
1681 if self
.IsBinaryModule
:
1684 self
.GenFfsList
= GenFfsList
1686 if not self
.IsLibrary
and CreateLibraryMakeFile
:
1687 for LibraryAutoGen
in self
.LibraryAutoGenList
:
1688 LibraryAutoGen
.CreateMakeFile()
1689 # Don't enable if hash feature enabled, CanSkip uses timestamps to determine build skipping
1690 if not GlobalData
.gUseHashCache
and self
.CanSkip():
1693 if len(self
.CustomMakefile
) == 0:
1694 Makefile
= GenMake
.ModuleMakefile(self
)
1696 Makefile
= GenMake
.CustomMakefile(self
)
1697 if Makefile
.Generate():
1698 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated makefile for module %s [%s]" %
1699 (self
.Name
, self
.Arch
))
1701 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Skipped the generation of makefile for module %s [%s]" %
1702 (self
.Name
, self
.Arch
))
1706 def CopyBinaryFiles(self
):
1707 for File
in self
.Module
.Binaries
:
1709 DstPath
= os
.path
.join(self
.OutputDir
, os
.path
.basename(SrcPath
))
1710 CopyLongFilePath(SrcPath
, DstPath
)
1711 ## Create autogen code for the module and its dependent libraries
1713 # @param CreateLibraryCodeFile Flag indicating if or not the code of
1714 # dependent libraries will be created
1716 def CreateCodeFile(self
, CreateLibraryCodeFile
=True):
1717 if self
.IsCodeFileCreated
:
1720 # Need to generate PcdDatabase even PcdDriver is binarymodule
1721 if self
.IsBinaryModule
and self
.PcdIsDriver
!= '':
1722 CreatePcdDatabaseCode(self
, TemplateString(), TemplateString())
1724 if self
.IsBinaryModule
:
1726 self
.CopyBinaryFiles()
1729 if not self
.IsLibrary
and CreateLibraryCodeFile
:
1730 for LibraryAutoGen
in self
.LibraryAutoGenList
:
1731 LibraryAutoGen
.CreateCodeFile()
1733 # Don't enable if hash feature enabled, CanSkip uses timestamps to determine build skipping
1734 if not GlobalData
.gUseHashCache
and self
.CanSkip():
1738 IgoredAutoGenList
= []
1740 for File
in self
.AutoGenFileList
:
1741 if GenC
.Generate(File
.Path
, self
.AutoGenFileList
[File
], File
.IsBinary
):
1742 AutoGenList
.append(str(File
))
1744 IgoredAutoGenList
.append(str(File
))
1747 for ModuleType
in self
.DepexList
:
1748 # Ignore empty [depex] section or [depex] section for SUP_MODULE_USER_DEFINED module
1749 if len(self
.DepexList
[ModuleType
]) == 0 or ModuleType
== SUP_MODULE_USER_DEFINED
or ModuleType
== SUP_MODULE_HOST_APPLICATION
:
1752 Dpx
= GenDepex
.DependencyExpression(self
.DepexList
[ModuleType
], ModuleType
, True)
1753 DpxFile
= gAutoGenDepexFileName
% {"module_name" : self
.Name
}
1755 if len(Dpx
.PostfixNotation
) != 0:
1756 self
.DepexGenerated
= True
1758 if Dpx
.Generate(path
.join(self
.OutputDir
, DpxFile
)):
1759 AutoGenList
.append(str(DpxFile
))
1761 IgoredAutoGenList
.append(str(DpxFile
))
1763 if IgoredAutoGenList
== []:
1764 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated [%s] files for module %s [%s]" %
1765 (" ".join(AutoGenList
), self
.Name
, self
.Arch
))
1766 elif AutoGenList
== []:
1767 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Skipped the generation of [%s] files for module %s [%s]" %
1768 (" ".join(IgoredAutoGenList
), self
.Name
, self
.Arch
))
1770 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "Generated [%s] (skipped %s) files for module %s [%s]" %
1771 (" ".join(AutoGenList
), " ".join(IgoredAutoGenList
), self
.Name
, self
.Arch
))
1773 self
.IsCodeFileCreated
= True
1776 ## Summarize the ModuleAutoGen objects of all libraries used by this module
1778 def LibraryAutoGenList(self
):
1780 for Library
in self
.DependentLibraryList
:
1787 self
.PlatformInfo
.MetaFile
,
1791 if La
not in RetVal
:
1793 for Lib
in La
.CodaTargetList
:
1794 self
._ApplyBuildRule
(Lib
.Target
, TAB_UNKNOWN_FILE
)
1797 def GenModuleHash(self
):
1798 # Initialize a dictionary for each arch type
1799 if self
.Arch
not in GlobalData
.gModuleHash
:
1800 GlobalData
.gModuleHash
[self
.Arch
] = {}
1802 # Early exit if module or library has been hashed and is in memory
1803 if self
.Name
in GlobalData
.gModuleHash
[self
.Arch
]:
1804 return GlobalData
.gModuleHash
[self
.Arch
][self
.Name
].encode('utf-8')
1806 # Initialze hash object
1809 # Add Platform level hash
1810 m
.update(GlobalData
.gPlatformHash
.encode('utf-8'))
1812 # Add Package level hash
1813 if self
.DependentPackageList
:
1814 for Pkg
in sorted(self
.DependentPackageList
, key
=lambda x
: x
.PackageName
):
1815 if Pkg
.PackageName
in GlobalData
.gPackageHash
:
1816 m
.update(GlobalData
.gPackageHash
[Pkg
.PackageName
].encode('utf-8'))
1819 if self
.LibraryAutoGenList
:
1820 for Lib
in sorted(self
.LibraryAutoGenList
, key
=lambda x
: x
.Name
):
1821 if Lib
.Name
not in GlobalData
.gModuleHash
[self
.Arch
]:
1823 m
.update(GlobalData
.gModuleHash
[self
.Arch
][Lib
.Name
].encode('utf-8'))
1826 f
= open(str(self
.MetaFile
), 'rb')
1831 # Add Module's source files
1832 if self
.SourceFileList
:
1833 for File
in sorted(self
.SourceFileList
, key
=lambda x
: str(x
)):
1834 f
= open(str(File
), 'rb')
1839 GlobalData
.gModuleHash
[self
.Arch
][self
.Name
] = m
.hexdigest()
1841 return GlobalData
.gModuleHash
[self
.Arch
][self
.Name
].encode('utf-8')
1843 ## Decide whether we can skip the ModuleAutoGen process
1844 def CanSkipbyHash(self
):
1845 # Hashing feature is off
1846 if not GlobalData
.gUseHashCache
:
1849 # Initialize a dictionary for each arch type
1850 if self
.Arch
not in GlobalData
.gBuildHashSkipTracking
:
1851 GlobalData
.gBuildHashSkipTracking
[self
.Arch
] = dict()
1853 # If library or Module is binary do not skip by hash
1854 if self
.IsBinaryModule
:
1857 # .inc is contains binary information so do not skip by hash as well
1858 for f_ext
in self
.SourceFileList
:
1859 if '.inc' in str(f_ext
):
1862 # Use Cache, if exists and if Module has a copy in cache
1863 if GlobalData
.gBinCacheSource
and self
.AttemptModuleCacheCopy():
1866 # Early exit for libraries that haven't yet finished building
1867 HashFile
= path
.join(self
.BuildDir
, self
.Name
+ ".hash")
1868 if self
.IsLibrary
and not os
.path
.exists(HashFile
):
1871 # Return a Boolean based on if can skip by hash, either from memory or from IO.
1872 if self
.Name
not in GlobalData
.gBuildHashSkipTracking
[self
.Arch
]:
1873 # If hashes are the same, SaveFileOnChange() will return False.
1874 GlobalData
.gBuildHashSkipTracking
[self
.Arch
][self
.Name
] = not SaveFileOnChange(HashFile
, self
.GenModuleHash(), True)
1875 return GlobalData
.gBuildHashSkipTracking
[self
.Arch
][self
.Name
]
1877 return GlobalData
.gBuildHashSkipTracking
[self
.Arch
][self
.Name
]
1879 ## Decide whether we can skip the ModuleAutoGen process
1880 # If any source file is newer than the module than we cannot skip
1883 if self
.MakeFileDir
in GlobalData
.gSikpAutoGenCache
:
1885 if not os
.path
.exists(self
.TimeStampPath
):
1887 #last creation time of the module
1888 DstTimeStamp
= os
.stat(self
.TimeStampPath
)[8]
1890 SrcTimeStamp
= self
.Workspace
._SrcTimeStamp
1891 if SrcTimeStamp
> DstTimeStamp
:
1894 with
open(self
.TimeStampPath
,'r') as f
:
1896 source
= source
.rstrip('\n')
1897 if not os
.path
.exists(source
):
1899 if source
not in ModuleAutoGen
.TimeDict
:
1900 ModuleAutoGen
.TimeDict
[source
] = os
.stat(source
)[8]
1901 if ModuleAutoGen
.TimeDict
[source
] > DstTimeStamp
:
1903 GlobalData
.gSikpAutoGenCache
.add(self
.MakeFileDir
)
1907 def TimeStampPath(self
):
1908 return os
.path
.join(self
.MakeFileDir
, 'AutoGenTimeStamp')