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