]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/AutoGen/ModuleAutoGen.py
d19c03862094910172fe0d38e5b2d4fafe3379f4
[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
30 ## Mapping Makefile type
31 gMakeTypeMap = {TAB_COMPILER_MSFT:"nmake", "GCC":"gmake"}
32 #
33 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT
34 # is the former use /I , the Latter used -I to specify include directories
35 #
36 gBuildOptIncludePatternMsft = re.compile(r"(?:.*?)/I[ \t]*([^ ]*)", re.MULTILINE | re.DOTALL)
37 gBuildOptIncludePatternOther = re.compile(r"(?:.*?)-I[ \t]*([^ ]*)", re.MULTILINE | re.DOTALL)
38
39 ## default file name for AutoGen
40 gAutoGenCodeFileName = "AutoGen.c"
41 gAutoGenHeaderFileName = "AutoGen.h"
42 gAutoGenStringFileName = "%(module_name)sStrDefs.h"
43 gAutoGenStringFormFileName = "%(module_name)sStrDefs.hpk"
44 gAutoGenDepexFileName = "%(module_name)s.depex"
45 gAutoGenImageDefFileName = "%(module_name)sImgDefs.h"
46 gAutoGenIdfFileName = "%(module_name)sIdf.hpk"
47 gInfSpecVersion = "0x00010017"
48
49 #
50 # Match name = variable
51 #
52 gEfiVarStoreNamePattern = re.compile("\s*name\s*=\s*(\w+)")
53 #
54 # The format of guid in efivarstore statement likes following and must be correct:
55 # guid = {0xA04A27f4, 0xDF00, 0x4D42, {0xB5, 0x52, 0x39, 0x51, 0x13, 0x02, 0x11, 0x3D}}
56 #
57 gEfiVarStoreGuidPattern = re.compile("\s*guid\s*=\s*({.*?{.*?}\s*})")
58
59 #
60 # Template string to generic AsBuilt INF
61 #
62 gAsBuiltInfHeaderString = TemplateString("""${header_comments}
63
64 # DO NOT EDIT
65 # FILE auto-generated
66
67 [Defines]
68 INF_VERSION = ${module_inf_version}
69 BASE_NAME = ${module_name}
70 FILE_GUID = ${module_guid}
71 MODULE_TYPE = ${module_module_type}${BEGIN}
72 VERSION_STRING = ${module_version_string}${END}${BEGIN}
73 PCD_IS_DRIVER = ${pcd_is_driver_string}${END}${BEGIN}
74 UEFI_SPECIFICATION_VERSION = ${module_uefi_specification_version}${END}${BEGIN}
75 PI_SPECIFICATION_VERSION = ${module_pi_specification_version}${END}${BEGIN}
76 ENTRY_POINT = ${module_entry_point}${END}${BEGIN}
77 UNLOAD_IMAGE = ${module_unload_image}${END}${BEGIN}
78 CONSTRUCTOR = ${module_constructor}${END}${BEGIN}
79 DESTRUCTOR = ${module_destructor}${END}${BEGIN}
80 SHADOW = ${module_shadow}${END}${BEGIN}
81 PCI_VENDOR_ID = ${module_pci_vendor_id}${END}${BEGIN}
82 PCI_DEVICE_ID = ${module_pci_device_id}${END}${BEGIN}
83 PCI_CLASS_CODE = ${module_pci_class_code}${END}${BEGIN}
84 PCI_REVISION = ${module_pci_revision}${END}${BEGIN}
85 BUILD_NUMBER = ${module_build_number}${END}${BEGIN}
86 SPEC = ${module_spec}${END}${BEGIN}
87 UEFI_HII_RESOURCE_SECTION = ${module_uefi_hii_resource_section}${END}${BEGIN}
88 MODULE_UNI_FILE = ${module_uni_file}${END}
89
90 [Packages.${module_arch}]${BEGIN}
91 ${package_item}${END}
92
93 [Binaries.${module_arch}]${BEGIN}
94 ${binary_item}${END}
95
96 [PatchPcd.${module_arch}]${BEGIN}
97 ${patchablepcd_item}
98 ${END}
99
100 [Protocols.${module_arch}]${BEGIN}
101 ${protocol_item}
102 ${END}
103
104 [Ppis.${module_arch}]${BEGIN}
105 ${ppi_item}
106 ${END}
107
108 [Guids.${module_arch}]${BEGIN}
109 ${guid_item}
110 ${END}
111
112 [PcdEx.${module_arch}]${BEGIN}
113 ${pcd_item}
114 ${END}
115
116 [LibraryClasses.${module_arch}]
117 ## @LIB_INSTANCES${BEGIN}
118 # ${libraryclasses_item}${END}
119
120 ${depexsection_item}
121
122 ${userextension_tianocore_item}
123
124 ${tail_comments}
125
126 [BuildOptions.${module_arch}]
127 ## @AsBuilt${BEGIN}
128 ## ${flags_item}${END}
129 """)
130 #
131 # extend lists contained in a dictionary with lists stored in another dictionary
132 # if CopyToDict is not derived from DefaultDict(list) then this may raise exception
133 #
134 def ExtendCopyDictionaryLists(CopyToDict, CopyFromDict):
135 for Key in CopyFromDict:
136 CopyToDict[Key].extend(CopyFromDict[Key])
137
138 # Create a directory specified by a set of path elements and return the full path
139 def _MakeDir(PathList):
140 RetVal = path.join(*PathList)
141 CreateDirectory(RetVal)
142 return RetVal
143
144 #
145 # Convert string to C format array
146 #
147 def _ConvertStringToByteArray(Value):
148 Value = Value.strip()
149 if not Value:
150 return None
151 if Value[0] == '{':
152 if not Value.endswith('}'):
153 return None
154 Value = Value.replace(' ', '').replace('{', '').replace('}', '')
155 ValFields = Value.split(',')
156 try:
157 for Index in range(len(ValFields)):
158 ValFields[Index] = str(int(ValFields[Index], 0))
159 except ValueError:
160 return None
161 Value = '{' + ','.join(ValFields) + '}'
162 return Value
163
164 Unicode = False
165 if Value.startswith('L"'):
166 if not Value.endswith('"'):
167 return None
168 Value = Value[1:]
169 Unicode = True
170 elif not Value.startswith('"') or not Value.endswith('"'):
171 return None
172
173 Value = eval(Value) # translate escape character
174 NewValue = '{'
175 for Index in range(0, len(Value)):
176 if Unicode:
177 NewValue = NewValue + str(ord(Value[Index]) % 0x10000) + ','
178 else:
179 NewValue = NewValue + str(ord(Value[Index]) % 0x100) + ','
180 Value = NewValue + '0}'
181 return Value
182
183 ## ModuleAutoGen class
184 #
185 # This class encapsules the AutoGen behaviors for the build tools. In addition to
186 # the generation of AutoGen.h and AutoGen.c, it will generate *.depex file according
187 # to the [depex] section in module's inf file.
188 #
189 class ModuleAutoGen(AutoGen):
190 # call super().__init__ then call the worker function with different parameter count
191 def __init__(self, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):
192 if not hasattr(self, "_Init"):
193 self._InitWorker(Workspace, MetaFile, Target, Toolchain, Arch, *args)
194 self._Init = True
195
196 ## Cache the timestamps of metafiles of every module in a class attribute
197 #
198 TimeDict = {}
199
200 def __new__(cls, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs):
201 # check if this module is employed by active platform
202 if not PlatformInfo(Workspace, args[0], Target, Toolchain, Arch,args[-1]).ValidModule(MetaFile):
203 EdkLogger.verbose("Module [%s] for [%s] is not employed by active platform\n" \
204 % (MetaFile, Arch))
205 return None
206 return super(ModuleAutoGen, cls).__new__(cls, Workspace, MetaFile, Target, Toolchain, Arch, *args, **kwargs)
207
208 ## Initialize ModuleAutoGen
209 #
210 # @param Workspace EdkIIWorkspaceBuild object
211 # @param ModuleFile The path of module file
212 # @param Target Build target (DEBUG, RELEASE)
213 # @param Toolchain Name of tool chain
214 # @param Arch The arch the module supports
215 # @param PlatformFile Platform meta-file
216 #
217 def _InitWorker(self, Workspace, ModuleFile, Target, Toolchain, Arch, PlatformFile,DataPipe):
218 EdkLogger.debug(EdkLogger.DEBUG_9, "AutoGen module [%s] [%s]" % (ModuleFile, Arch))
219 GlobalData.gProcessingFile = "%s [%s, %s, %s]" % (ModuleFile, Arch, Toolchain, Target)
220
221 self.Workspace = None
222 self.WorkspaceDir = ""
223 self.PlatformInfo = None
224 self.DataPipe = DataPipe
225 self.__init_platform_info__()
226 self.MetaFile = ModuleFile
227 self.SourceDir = self.MetaFile.SubDir
228 self.SourceDir = mws.relpath(self.SourceDir, self.WorkspaceDir)
229
230 self.ToolChain = Toolchain
231 self.BuildTarget = Target
232 self.Arch = Arch
233 self.ToolChainFamily = self.PlatformInfo.ToolChainFamily
234 self.BuildRuleFamily = self.PlatformInfo.BuildRuleFamily
235
236 self.IsCodeFileCreated = False
237 self.IsAsBuiltInfCreated = False
238 self.DepexGenerated = False
239
240 self.BuildDatabase = self.Workspace.BuildDatabase
241 self.BuildRuleOrder = None
242 self.BuildTime = 0
243
244 self._GuidComments = OrderedListDict()
245 self._ProtocolComments = OrderedListDict()
246 self._PpiComments = OrderedListDict()
247 self._BuildTargets = None
248 self._IntroBuildTargetList = None
249 self._FinalBuildTargetList = None
250 self._FileTypes = None
251
252 self.AutoGenDepSet = set()
253 self.ReferenceModules = []
254 self.ConstPcd = {}
255
256 def __init_platform_info__(self):
257 pinfo = self.DataPipe.Get("P_Info")
258 self.Workspace = WorkSpaceInfo(pinfo.get("WorkspaceDir"),pinfo.get("ActivePlatform"),pinfo.get("Target"),pinfo.get("ToolChain"),pinfo.get("ArchList"))
259 self.WorkspaceDir = pinfo.get("WorkspaceDir")
260 self.PlatformInfo = PlatformInfo(self.Workspace,pinfo.get("ActivePlatform"),pinfo.get("Target"),pinfo.get("ToolChain"),pinfo.get("Arch"),self.DataPipe)
261 ## hash() operator of ModuleAutoGen
262 #
263 # The module file path and arch string will be used to represent
264 # hash value of this object
265 #
266 # @retval int Hash value of the module file path and arch
267 #
268 @cached_class_function
269 def __hash__(self):
270 return hash((self.MetaFile, self.Arch))
271 def __repr__(self):
272 return "%s [%s]" % (self.MetaFile, self.Arch)
273
274 # Get FixedAtBuild Pcds of this Module
275 @cached_property
276 def FixedAtBuildPcds(self):
277 RetVal = []
278 for Pcd in self.ModulePcdList:
279 if Pcd.Type != TAB_PCDS_FIXED_AT_BUILD:
280 continue
281 if Pcd not in RetVal:
282 RetVal.append(Pcd)
283 return RetVal
284
285 @cached_property
286 def FixedVoidTypePcds(self):
287 RetVal = {}
288 for Pcd in self.FixedAtBuildPcds:
289 if Pcd.DatumType == TAB_VOID:
290 if '.'.join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName)) not in RetVal:
291 RetVal['.'.join((Pcd.TokenSpaceGuidCName, Pcd.TokenCName))] = Pcd.DefaultValue
292 return RetVal
293
294 @property
295 def UniqueBaseName(self):
296 ModuleNames = self.DataPipe.Get("M_Name")
297 if not ModuleNames:
298 return self.Name
299 return ModuleNames.get(self.Name,self.Name)
300
301 # Macros could be used in build_rule.txt (also Makefile)
302 @cached_property
303 def Macros(self):
304 return OrderedDict((
305 ("WORKSPACE" ,self.WorkspaceDir),
306 ("MODULE_NAME" ,self.Name),
307 ("MODULE_NAME_GUID" ,self.UniqueBaseName),
308 ("MODULE_GUID" ,self.Guid),
309 ("MODULE_VERSION" ,self.Version),
310 ("MODULE_TYPE" ,self.ModuleType),
311 ("MODULE_FILE" ,str(self.MetaFile)),
312 ("MODULE_FILE_BASE_NAME" ,self.MetaFile.BaseName),
313 ("MODULE_RELATIVE_DIR" ,self.SourceDir),
314 ("MODULE_DIR" ,self.SourceDir),
315 ("BASE_NAME" ,self.Name),
316 ("ARCH" ,self.Arch),
317 ("TOOLCHAIN" ,self.ToolChain),
318 ("TOOLCHAIN_TAG" ,self.ToolChain),
319 ("TOOL_CHAIN_TAG" ,self.ToolChain),
320 ("TARGET" ,self.BuildTarget),
321 ("BUILD_DIR" ,self.PlatformInfo.BuildDir),
322 ("BIN_DIR" ,os.path.join(self.PlatformInfo.BuildDir, self.Arch)),
323 ("LIB_DIR" ,os.path.join(self.PlatformInfo.BuildDir, self.Arch)),
324 ("MODULE_BUILD_DIR" ,self.BuildDir),
325 ("OUTPUT_DIR" ,self.OutputDir),
326 ("DEBUG_DIR" ,self.DebugDir),
327 ("DEST_DIR_OUTPUT" ,self.OutputDir),
328 ("DEST_DIR_DEBUG" ,self.DebugDir),
329 ("PLATFORM_NAME" ,self.PlatformInfo.Name),
330 ("PLATFORM_GUID" ,self.PlatformInfo.Guid),
331 ("PLATFORM_VERSION" ,self.PlatformInfo.Version),
332 ("PLATFORM_RELATIVE_DIR" ,self.PlatformInfo.SourceDir),
333 ("PLATFORM_DIR" ,mws.join(self.WorkspaceDir, self.PlatformInfo.SourceDir)),
334 ("PLATFORM_OUTPUT_DIR" ,self.PlatformInfo.OutputDir),
335 ("FFS_OUTPUT_DIR" ,self.FfsOutputDir)
336 ))
337
338 ## Return the module build data object
339 @cached_property
340 def Module(self):
341 return self.BuildDatabase[self.MetaFile, self.Arch, self.BuildTarget, self.ToolChain]
342
343 ## Return the module name
344 @cached_property
345 def Name(self):
346 return self.Module.BaseName
347
348 ## Return the module DxsFile if exist
349 @cached_property
350 def DxsFile(self):
351 return self.Module.DxsFile
352
353 ## Return the module meta-file GUID
354 @cached_property
355 def Guid(self):
356 #
357 # To build same module more than once, the module path with FILE_GUID overridden has
358 # the file name FILE_GUIDmodule.inf, but the relative path (self.MetaFile.File) is the real path
359 # in DSC. The overridden GUID can be retrieved from file name
360 #
361 if os.path.basename(self.MetaFile.File) != os.path.basename(self.MetaFile.Path):
362 #
363 # Length of GUID is 36
364 #
365 return os.path.basename(self.MetaFile.Path)[:36]
366 return self.Module.Guid
367
368 ## Return the module version
369 @cached_property
370 def Version(self):
371 return self.Module.Version
372
373 ## Return the module type
374 @cached_property
375 def ModuleType(self):
376 return self.Module.ModuleType
377
378 ## Return the component type (for Edk.x style of module)
379 @cached_property
380 def ComponentType(self):
381 return self.Module.ComponentType
382
383 ## Return the build type
384 @cached_property
385 def BuildType(self):
386 return self.Module.BuildType
387
388 ## Return the PCD_IS_DRIVER setting
389 @cached_property
390 def PcdIsDriver(self):
391 return self.Module.PcdIsDriver
392
393 ## Return the autogen version, i.e. module meta-file version
394 @cached_property
395 def AutoGenVersion(self):
396 return self.Module.AutoGenVersion
397
398 ## Check if the module is library or not
399 @cached_property
400 def IsLibrary(self):
401 return bool(self.Module.LibraryClass)
402
403 ## Check if the module is binary module or not
404 @cached_property
405 def IsBinaryModule(self):
406 return self.Module.IsBinaryModule
407
408 ## Return the directory to store intermediate files of the module
409 @cached_property
410 def BuildDir(self):
411 return _MakeDir((
412 self.PlatformInfo.BuildDir,
413 self.Arch,
414 self.SourceDir,
415 self.MetaFile.BaseName
416 ))
417
418 ## Return the directory to store the intermediate object files of the module
419 @cached_property
420 def OutputDir(self):
421 return _MakeDir((self.BuildDir, "OUTPUT"))
422
423 ## Return the directory path to store ffs file
424 @cached_property
425 def FfsOutputDir(self):
426 if GlobalData.gFdfParser:
427 return path.join(self.PlatformInfo.BuildDir, TAB_FV_DIRECTORY, "Ffs", self.Guid + self.Name)
428 return ''
429
430 ## Return the directory to store auto-gened source files of the module
431 @cached_property
432 def DebugDir(self):
433 return _MakeDir((self.BuildDir, "DEBUG"))
434
435 ## Return the path of custom file
436 @cached_property
437 def CustomMakefile(self):
438 RetVal = {}
439 for Type in self.Module.CustomMakefile:
440 MakeType = gMakeTypeMap[Type] if Type in gMakeTypeMap else 'nmake'
441 File = os.path.join(self.SourceDir, self.Module.CustomMakefile[Type])
442 RetVal[MakeType] = File
443 return RetVal
444
445 ## Return the directory of the makefile
446 #
447 # @retval string The directory string of module's makefile
448 #
449 @cached_property
450 def MakeFileDir(self):
451 return self.BuildDir
452
453 ## Return build command string
454 #
455 # @retval string Build command string
456 #
457 @cached_property
458 def BuildCommand(self):
459 return self.PlatformInfo.BuildCommand
460
461 ## Get object list of all packages the module and its dependent libraries belong to
462 #
463 # @retval list The list of package object
464 #
465 @cached_property
466 def DerivedPackageList(self):
467 PackageList = []
468 for M in [self.Module] + self.DependentLibraryList:
469 for Package in M.Packages:
470 if Package in PackageList:
471 continue
472 PackageList.append(Package)
473 return PackageList
474
475 ## Get the depex string
476 #
477 # @return : a string contain all depex expression.
478 def _GetDepexExpresionString(self):
479 DepexStr = ''
480 DepexList = []
481 ## DPX_SOURCE IN Define section.
482 if self.Module.DxsFile:
483 return DepexStr
484 for M in [self.Module] + self.DependentLibraryList:
485 Filename = M.MetaFile.Path
486 InfObj = InfSectionParser.InfSectionParser(Filename)
487 DepexExpressionList = InfObj.GetDepexExpresionList()
488 for DepexExpression in DepexExpressionList:
489 for key in DepexExpression:
490 Arch, ModuleType = key
491 DepexExpr = [x for x in DepexExpression[key] if not str(x).startswith('#')]
492 # the type of build module is USER_DEFINED.
493 # All different DEPEX section tags would be copied into the As Built INF file
494 # and there would be separate DEPEX section tags
495 if self.ModuleType.upper() == SUP_MODULE_USER_DEFINED or self.ModuleType.upper() == SUP_MODULE_HOST_APPLICATION:
496 if (Arch.upper() == self.Arch.upper()) and (ModuleType.upper() != TAB_ARCH_COMMON):
497 DepexList.append({(Arch, ModuleType): DepexExpr})
498 else:
499 if Arch.upper() == TAB_ARCH_COMMON or \
500 (Arch.upper() == self.Arch.upper() and \
501 ModuleType.upper() in [TAB_ARCH_COMMON, self.ModuleType.upper()]):
502 DepexList.append({(Arch, ModuleType): DepexExpr})
503
504 #the type of build module is USER_DEFINED.
505 if self.ModuleType.upper() == SUP_MODULE_USER_DEFINED or self.ModuleType.upper() == SUP_MODULE_HOST_APPLICATION:
506 for Depex in DepexList:
507 for key in Depex:
508 DepexStr += '[Depex.%s.%s]\n' % key
509 DepexStr += '\n'.join('# '+ val for val in Depex[key])
510 DepexStr += '\n\n'
511 if not DepexStr:
512 return '[Depex.%s]\n' % self.Arch
513 return DepexStr
514
515 #the type of build module not is USER_DEFINED.
516 Count = 0
517 for Depex in DepexList:
518 Count += 1
519 if DepexStr != '':
520 DepexStr += ' AND '
521 DepexStr += '('
522 for D in Depex.values():
523 DepexStr += ' '.join(val for val in D)
524 Index = DepexStr.find('END')
525 if Index > -1 and Index == len(DepexStr) - 3:
526 DepexStr = DepexStr[:-3]
527 DepexStr = DepexStr.strip()
528 DepexStr += ')'
529 if Count == 1:
530 DepexStr = DepexStr.lstrip('(').rstrip(')').strip()
531 if not DepexStr:
532 return '[Depex.%s]\n' % self.Arch
533 return '[Depex.%s]\n# ' % self.Arch + DepexStr
534
535 ## Merge dependency expression
536 #
537 # @retval list The token list of the dependency expression after parsed
538 #
539 @cached_property
540 def DepexList(self):
541 if self.DxsFile or self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:
542 return {}
543
544 DepexList = []
545 #
546 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expression
547 #
548 FixedVoidTypePcds = {}
549 for M in [self] + self.LibraryAutoGenList:
550 FixedVoidTypePcds.update(M.FixedVoidTypePcds)
551 for M in [self] + self.LibraryAutoGenList:
552 Inherited = False
553 for D in M.Module.Depex[self.Arch, self.ModuleType]:
554 if DepexList != []:
555 DepexList.append('AND')
556 DepexList.append('(')
557 #replace D with value if D is FixedAtBuild PCD
558 NewList = []
559 for item in D:
560 if '.' not in item:
561 NewList.append(item)
562 else:
563 try:
564 Value = FixedVoidTypePcds[item]
565 if len(Value.split(',')) != 16:
566 EdkLogger.error("build", FORMAT_INVALID,
567 "{} used in [Depex] section should be used as FixedAtBuild type and VOID* datum type and 16 bytes in the module.".format(item))
568 NewList.append(Value)
569 except:
570 EdkLogger.error("build", FORMAT_INVALID, "{} used in [Depex] section should be used as FixedAtBuild type and VOID* datum type in the module.".format(item))
571
572 DepexList.extend(NewList)
573 if DepexList[-1] == 'END': # no need of a END at this time
574 DepexList.pop()
575 DepexList.append(')')
576 Inherited = True
577 if Inherited:
578 EdkLogger.verbose("DEPEX[%s] (+%s) = %s" % (self.Name, M.Module.BaseName, DepexList))
579 if 'BEFORE' in DepexList or 'AFTER' in DepexList:
580 break
581 if len(DepexList) > 0:
582 EdkLogger.verbose('')
583 return {self.ModuleType:DepexList}
584
585 ## Merge dependency expression
586 #
587 # @retval list The token list of the dependency expression after parsed
588 #
589 @cached_property
590 def DepexExpressionDict(self):
591 if self.DxsFile or self.IsLibrary or TAB_DEPENDENCY_EXPRESSION_FILE in self.FileTypes:
592 return {}
593
594 DepexExpressionString = ''
595 #
596 # Append depex from dependent libraries, if not "BEFORE", "AFTER" expresion
597 #
598 for M in [self.Module] + self.DependentLibraryList:
599 Inherited = False
600 for D in M.DepexExpression[self.Arch, self.ModuleType]:
601 if DepexExpressionString != '':
602 DepexExpressionString += ' AND '
603 DepexExpressionString += '('
604 DepexExpressionString += D
605 DepexExpressionString = DepexExpressionString.rstrip('END').strip()
606 DepexExpressionString += ')'
607 Inherited = True
608 if Inherited:
609 EdkLogger.verbose("DEPEX[%s] (+%s) = %s" % (self.Name, M.BaseName, DepexExpressionString))
610 if 'BEFORE' in DepexExpressionString or 'AFTER' in DepexExpressionString:
611 break
612 if len(DepexExpressionString) > 0:
613 EdkLogger.verbose('')
614
615 return {self.ModuleType:DepexExpressionString}
616
617 # Get the tiano core user extension, it is contain dependent library.
618 # @retval: a list contain tiano core userextension.
619 #
620 def _GetTianoCoreUserExtensionList(self):
621 TianoCoreUserExtentionList = []
622 for M in [self.Module] + self.DependentLibraryList:
623 Filename = M.MetaFile.Path
624 InfObj = InfSectionParser.InfSectionParser(Filename)
625 TianoCoreUserExtenList = InfObj.GetUserExtensionTianoCore()
626 for TianoCoreUserExtent in TianoCoreUserExtenList:
627 for Section in TianoCoreUserExtent:
628 ItemList = Section.split(TAB_SPLIT)
629 Arch = self.Arch
630 if len(ItemList) == 4:
631 Arch = ItemList[3]
632 if Arch.upper() == TAB_ARCH_COMMON or Arch.upper() == self.Arch.upper():
633 TianoCoreList = []
634 TianoCoreList.extend([TAB_SECTION_START + Section + TAB_SECTION_END])
635 TianoCoreList.extend(TianoCoreUserExtent[Section][:])
636 TianoCoreList.append('\n')
637 TianoCoreUserExtentionList.append(TianoCoreList)
638
639 return TianoCoreUserExtentionList
640
641 ## Return the list of specification version required for the module
642 #
643 # @retval list The list of specification defined in module file
644 #
645 @cached_property
646 def Specification(self):
647 return self.Module.Specification
648
649 ## Tool option for the module build
650 #
651 # @param PlatformInfo The object of PlatformBuildInfo
652 # @retval dict The dict containing valid options
653 #
654 @cached_property
655 def BuildOption(self):
656 RetVal, self.BuildRuleOrder = self.PlatformInfo.ApplyBuildOption(self.Module)
657 if self.BuildRuleOrder:
658 self.BuildRuleOrder = ['.%s' % Ext for Ext in self.BuildRuleOrder.split()]
659 return RetVal
660
661 ## Get include path list from tool option for the module build
662 #
663 # @retval list The include path list
664 #
665 @cached_property
666 def BuildOptionIncPathList(self):
667 #
668 # Regular expression for finding Include Directories, the difference between MSFT and INTEL/GCC/RVCT
669 # is the former use /I , the Latter used -I to specify include directories
670 #
671 if self.PlatformInfo.ToolChainFamily in (TAB_COMPILER_MSFT):
672 BuildOptIncludeRegEx = gBuildOptIncludePatternMsft
673 elif self.PlatformInfo.ToolChainFamily in ('INTEL', 'GCC', 'RVCT'):
674 BuildOptIncludeRegEx = gBuildOptIncludePatternOther
675 else:
676 #
677 # New ToolChainFamily, don't known whether there is option to specify include directories
678 #
679 return []
680
681 RetVal = []
682 for Tool in ('CC', 'PP', 'VFRPP', 'ASLPP', 'ASLCC', 'APP', 'ASM'):
683 try:
684 FlagOption = self.BuildOption[Tool]['FLAGS']
685 except KeyError:
686 FlagOption = ''
687
688 if self.ToolChainFamily != 'RVCT':
689 IncPathList = [NormPath(Path, self.Macros) for Path in BuildOptIncludeRegEx.findall(FlagOption)]
690 else:
691 #
692 # RVCT may specify a list of directory seperated by commas
693 #
694 IncPathList = []
695 for Path in BuildOptIncludeRegEx.findall(FlagOption):
696 PathList = GetSplitList(Path, TAB_COMMA_SPLIT)
697 IncPathList.extend(NormPath(PathEntry, self.Macros) for PathEntry in PathList)
698
699 #
700 # EDK II modules must not reference header files outside of the packages they depend on or
701 # within the module's directory tree. Report error if violation.
702 #
703 if GlobalData.gDisableIncludePathCheck == False:
704 for Path in IncPathList:
705 if (Path not in self.IncludePathList) and (CommonPath([Path, self.MetaFile.Dir]) != self.MetaFile.Dir):
706 ErrMsg = "The include directory for the EDK II module in this line is invalid %s specified in %s FLAGS '%s'" % (Path, Tool, FlagOption)
707 EdkLogger.error("build",
708 PARAMETER_INVALID,
709 ExtraData=ErrMsg,
710 File=str(self.MetaFile))
711 RetVal += IncPathList
712 return RetVal
713
714 ## Return a list of files which can be built from source
715 #
716 # What kind of files can be built is determined by build rules in
717 # $(CONF_DIRECTORY)/build_rule.txt and toolchain family.
718 #
719 @cached_property
720 def SourceFileList(self):
721 RetVal = []
722 ToolChainTagSet = {"", TAB_STAR, self.ToolChain}
723 ToolChainFamilySet = {"", TAB_STAR, self.ToolChainFamily, self.BuildRuleFamily}
724 for F in self.Module.Sources:
725 # match tool chain
726 if F.TagName not in ToolChainTagSet:
727 EdkLogger.debug(EdkLogger.DEBUG_9, "The toolchain [%s] for processing file [%s] is found, "
728 "but [%s] is currently used" % (F.TagName, str(F), self.ToolChain))
729 continue
730 # match tool chain family or build rule family
731 if F.ToolChainFamily not in ToolChainFamilySet:
732 EdkLogger.debug(
733 EdkLogger.DEBUG_0,
734 "The file [%s] must be built by tools of [%s], " \
735 "but current toolchain family is [%s], buildrule family is [%s]" \
736 % (str(F), F.ToolChainFamily, self.ToolChainFamily, self.BuildRuleFamily))
737 continue
738
739 # add the file path into search path list for file including
740 if F.Dir not in self.IncludePathList:
741 self.IncludePathList.insert(0, F.Dir)
742 RetVal.append(F)
743
744 self._MatchBuildRuleOrder(RetVal)
745
746 for F in RetVal:
747 self._ApplyBuildRule(F, TAB_UNKNOWN_FILE)
748 return RetVal
749
750 def _MatchBuildRuleOrder(self, FileList):
751 Order_Dict = {}
752 self.BuildOption
753 for SingleFile in FileList:
754 if self.BuildRuleOrder and SingleFile.Ext in self.BuildRuleOrder and SingleFile.Ext in self.BuildRules:
755 key = SingleFile.Path.rsplit(SingleFile.Ext,1)[0]
756 if key in Order_Dict:
757 Order_Dict[key].append(SingleFile.Ext)
758 else:
759 Order_Dict[key] = [SingleFile.Ext]
760
761 RemoveList = []
762 for F in Order_Dict:
763 if len(Order_Dict[F]) > 1:
764 Order_Dict[F].sort(key=lambda i: self.BuildRuleOrder.index(i))
765 for Ext in Order_Dict[F][1:]:
766 RemoveList.append(F + Ext)
767
768 for item in RemoveList:
769 FileList.remove(item)
770
771 return FileList
772
773 ## Return the list of unicode files
774 @cached_property
775 def UnicodeFileList(self):
776 return self.FileTypes.get(TAB_UNICODE_FILE,[])
777
778 ## Return the list of vfr files
779 @cached_property
780 def VfrFileList(self):
781 return self.FileTypes.get(TAB_VFR_FILE, [])
782
783 ## Return the list of Image Definition files
784 @cached_property
785 def IdfFileList(self):
786 return self.FileTypes.get(TAB_IMAGE_FILE,[])
787
788 ## Return a list of files which can be built from binary
789 #
790 # "Build" binary files are just to copy them to build directory.
791 #
792 # @retval list The list of files which can be built later
793 #
794 @cached_property
795 def BinaryFileList(self):
796 RetVal = []
797 for F in self.Module.Binaries:
798 if F.Target not in [TAB_ARCH_COMMON, TAB_STAR] and F.Target != self.BuildTarget:
799 continue
800 RetVal.append(F)
801 self._ApplyBuildRule(F, F.Type, BinaryFileList=RetVal)
802 return RetVal
803
804 @cached_property
805 def BuildRules(self):
806 RetVal = {}
807 BuildRuleDatabase = self.PlatformInfo.BuildRule
808 for Type in BuildRuleDatabase.FileTypeList:
809 #first try getting build rule by BuildRuleFamily
810 RuleObject = BuildRuleDatabase[Type, self.BuildType, self.Arch, self.BuildRuleFamily]
811 if not RuleObject:
812 # build type is always module type, but ...
813 if self.ModuleType != self.BuildType:
814 RuleObject = BuildRuleDatabase[Type, self.ModuleType, self.Arch, self.BuildRuleFamily]
815 #second try getting build rule by ToolChainFamily
816 if not RuleObject:
817 RuleObject = BuildRuleDatabase[Type, self.BuildType, self.Arch, self.ToolChainFamily]
818 if not RuleObject:
819 # build type is always module type, but ...
820 if self.ModuleType != self.BuildType:
821 RuleObject = BuildRuleDatabase[Type, self.ModuleType, self.Arch, self.ToolChainFamily]
822 if not RuleObject:
823 continue
824 RuleObject = RuleObject.Instantiate(self.Macros)
825 RetVal[Type] = RuleObject
826 for Ext in RuleObject.SourceFileExtList:
827 RetVal[Ext] = RuleObject
828 return RetVal
829
830 def _ApplyBuildRule(self, File, FileType, BinaryFileList=None):
831 if self._BuildTargets is None:
832 self._IntroBuildTargetList = set()
833 self._FinalBuildTargetList = set()
834 self._BuildTargets = defaultdict(set)
835 self._FileTypes = defaultdict(set)
836
837 if not BinaryFileList:
838 BinaryFileList = self.BinaryFileList
839
840 SubDirectory = os.path.join(self.OutputDir, File.SubDir)
841 if not os.path.exists(SubDirectory):
842 CreateDirectory(SubDirectory)
843 LastTarget = None
844 RuleChain = set()
845 SourceList = [File]
846 Index = 0
847 #
848 # Make sure to get build rule order value
849 #
850 self.BuildOption
851
852 while Index < len(SourceList):
853 Source = SourceList[Index]
854 Index = Index + 1
855
856 if Source != File:
857 CreateDirectory(Source.Dir)
858
859 if File.IsBinary and File == Source and File in BinaryFileList:
860 # Skip all files that are not binary libraries
861 if not self.IsLibrary:
862 continue
863 RuleObject = self.BuildRules[TAB_DEFAULT_BINARY_FILE]
864 elif FileType in self.BuildRules:
865 RuleObject = self.BuildRules[FileType]
866 elif Source.Ext in self.BuildRules:
867 RuleObject = self.BuildRules[Source.Ext]
868 else:
869 # stop at no more rules
870 if LastTarget:
871 self._FinalBuildTargetList.add(LastTarget)
872 break
873
874 FileType = RuleObject.SourceFileType
875 self._FileTypes[FileType].add(Source)
876
877 # stop at STATIC_LIBRARY for library
878 if self.IsLibrary and FileType == TAB_STATIC_LIBRARY:
879 if LastTarget:
880 self._FinalBuildTargetList.add(LastTarget)
881 break
882
883 Target = RuleObject.Apply(Source, self.BuildRuleOrder)
884 if not Target:
885 if LastTarget:
886 self._FinalBuildTargetList.add(LastTarget)
887 break
888 elif not Target.Outputs:
889 # Only do build for target with outputs
890 self._FinalBuildTargetList.add(Target)
891
892 self._BuildTargets[FileType].add(Target)
893
894 if not Source.IsBinary and Source == File:
895 self._IntroBuildTargetList.add(Target)
896
897 # to avoid cyclic rule
898 if FileType in RuleChain:
899 break
900
901 RuleChain.add(FileType)
902 SourceList.extend(Target.Outputs)
903 LastTarget = Target
904 FileType = TAB_UNKNOWN_FILE
905
906 @cached_property
907 def Targets(self):
908 if self._BuildTargets is None:
909 self._IntroBuildTargetList = set()
910 self._FinalBuildTargetList = set()
911 self._BuildTargets = defaultdict(set)
912 self._FileTypes = defaultdict(set)
913
914 #TRICK: call SourceFileList property to apply build rule for source files
915 self.SourceFileList
916
917 #TRICK: call _GetBinaryFileList to apply build rule for binary files
918 self.BinaryFileList
919
920 return self._BuildTargets
921
922 @cached_property
923 def IntroTargetList(self):
924 self.Targets
925 return self._IntroBuildTargetList
926
927 @cached_property
928 def CodaTargetList(self):
929 self.Targets
930 return self._FinalBuildTargetList
931
932 @cached_property
933 def FileTypes(self):
934 self.Targets
935 return self._FileTypes
936
937 ## Get the list of package object the module depends on
938 #
939 # @retval list The package object list
940 #
941 @cached_property
942 def DependentPackageList(self):
943 return self.Module.Packages
944
945 ## Return the list of auto-generated code file
946 #
947 # @retval list The list of auto-generated file
948 #
949 @cached_property
950 def AutoGenFileList(self):
951 AutoGenUniIdf = self.BuildType != 'UEFI_HII'
952 UniStringBinBuffer = BytesIO()
953 IdfGenBinBuffer = BytesIO()
954 RetVal = {}
955 AutoGenC = TemplateString()
956 AutoGenH = TemplateString()
957 StringH = TemplateString()
958 StringIdf = TemplateString()
959 GenC.CreateCode(self, AutoGenC, AutoGenH, StringH, AutoGenUniIdf, UniStringBinBuffer, StringIdf, AutoGenUniIdf, IdfGenBinBuffer)
960 #
961 # AutoGen.c is generated if there are library classes in inf, or there are object files
962 #
963 if str(AutoGenC) != "" and (len(self.Module.LibraryClasses) > 0
964 or TAB_OBJECT_FILE in self.FileTypes):
965 AutoFile = PathClass(gAutoGenCodeFileName, self.DebugDir)
966 RetVal[AutoFile] = str(AutoGenC)
967 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)
968 if str(AutoGenH) != "":
969 AutoFile = PathClass(gAutoGenHeaderFileName, self.DebugDir)
970 RetVal[AutoFile] = str(AutoGenH)
971 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)
972 if str(StringH) != "":
973 AutoFile = PathClass(gAutoGenStringFileName % {"module_name":self.Name}, self.DebugDir)
974 RetVal[AutoFile] = str(StringH)
975 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)
976 if UniStringBinBuffer is not None and UniStringBinBuffer.getvalue() != b"":
977 AutoFile = PathClass(gAutoGenStringFormFileName % {"module_name":self.Name}, self.OutputDir)
978 RetVal[AutoFile] = UniStringBinBuffer.getvalue()
979 AutoFile.IsBinary = True
980 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)
981 if UniStringBinBuffer is not None:
982 UniStringBinBuffer.close()
983 if str(StringIdf) != "":
984 AutoFile = PathClass(gAutoGenImageDefFileName % {"module_name":self.Name}, self.DebugDir)
985 RetVal[AutoFile] = str(StringIdf)
986 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)
987 if IdfGenBinBuffer is not None and IdfGenBinBuffer.getvalue() != b"":
988 AutoFile = PathClass(gAutoGenIdfFileName % {"module_name":self.Name}, self.OutputDir)
989 RetVal[AutoFile] = IdfGenBinBuffer.getvalue()
990 AutoFile.IsBinary = True
991 self._ApplyBuildRule(AutoFile, TAB_UNKNOWN_FILE)
992 if IdfGenBinBuffer is not None:
993 IdfGenBinBuffer.close()
994 return RetVal
995
996 ## Return the list of library modules explicitly or implicitly used by this module
997 @cached_property
998 def DependentLibraryList(self):
999 # only merge library classes and PCD for non-library module
1000 if self.IsLibrary:
1001 return []
1002 return self.PlatformInfo.ApplyLibraryInstance(self.Module)
1003
1004 ## Get the list of PCDs from current module
1005 #
1006 # @retval list The list of PCD
1007 #
1008 @cached_property
1009 def ModulePcdList(self):
1010 # apply PCD settings from platform
1011 RetVal = self.PlatformInfo.ApplyPcdSetting(self.Module, self.Module.Pcds)
1012
1013 return RetVal
1014 @cached_property
1015 def _PcdComments(self):
1016 ReVal = OrderedListDict()
1017 ExtendCopyDictionaryLists(ReVal, self.Module.PcdComments)
1018 if not self.IsLibrary:
1019 for Library in self.DependentLibraryList:
1020 ExtendCopyDictionaryLists(ReVal, Library.PcdComments)
1021 return ReVal
1022
1023 ## Get the list of PCDs from dependent libraries
1024 #
1025 # @retval list The list of PCD
1026 #
1027 @cached_property
1028 def LibraryPcdList(self):
1029 if self.IsLibrary:
1030 return []
1031 RetVal = []
1032 Pcds = set()
1033 # get PCDs from dependent libraries
1034 for Library in self.DependentLibraryList:
1035 PcdsInLibrary = OrderedDict()
1036 for Key in Library.Pcds:
1037 # skip duplicated PCDs
1038 if Key in self.Module.Pcds or Key in Pcds:
1039 continue
1040 Pcds.add(Key)
1041 PcdsInLibrary[Key] = copy.copy(Library.Pcds[Key])
1042 RetVal.extend(self.PlatformInfo.ApplyPcdSetting(self.Module, PcdsInLibrary, Library=Library))
1043 return RetVal
1044
1045 ## Get the GUID value mapping
1046 #
1047 # @retval dict The mapping between GUID cname and its value
1048 #
1049 @cached_property
1050 def GuidList(self):
1051 RetVal = self.Module.Guids
1052 for Library in self.DependentLibraryList:
1053 RetVal.update(Library.Guids)
1054 ExtendCopyDictionaryLists(self._GuidComments, Library.GuidComments)
1055 ExtendCopyDictionaryLists(self._GuidComments, self.Module.GuidComments)
1056 return RetVal
1057
1058 @cached_property
1059 def GetGuidsUsedByPcd(self):
1060 RetVal = OrderedDict(self.Module.GetGuidsUsedByPcd())
1061 for Library in self.DependentLibraryList:
1062 RetVal.update(Library.GetGuidsUsedByPcd())
1063 return RetVal
1064 ## Get the protocol value mapping
1065 #
1066 # @retval dict The mapping between protocol cname and its value
1067 #
1068 @cached_property
1069 def ProtocolList(self):
1070 RetVal = OrderedDict(self.Module.Protocols)
1071 for Library in self.DependentLibraryList:
1072 RetVal.update(Library.Protocols)
1073 ExtendCopyDictionaryLists(self._ProtocolComments, Library.ProtocolComments)
1074 ExtendCopyDictionaryLists(self._ProtocolComments, self.Module.ProtocolComments)
1075 return RetVal
1076
1077 ## Get the PPI value mapping
1078 #
1079 # @retval dict The mapping between PPI cname and its value
1080 #
1081 @cached_property
1082 def PpiList(self):
1083 RetVal = OrderedDict(self.Module.Ppis)
1084 for Library in self.DependentLibraryList:
1085 RetVal.update(Library.Ppis)
1086 ExtendCopyDictionaryLists(self._PpiComments, Library.PpiComments)
1087 ExtendCopyDictionaryLists(self._PpiComments, self.Module.PpiComments)
1088 return RetVal
1089
1090 ## Get the list of include search path
1091 #
1092 # @retval list The list path
1093 #
1094 @cached_property
1095 def IncludePathList(self):
1096 RetVal = []
1097 RetVal.append(self.MetaFile.Dir)
1098 RetVal.append(self.DebugDir)
1099
1100 for Package in self.Module.Packages:
1101 PackageDir = mws.join(self.WorkspaceDir, Package.MetaFile.Dir)
1102 if PackageDir not in RetVal:
1103 RetVal.append(PackageDir)
1104 IncludesList = Package.Includes
1105 if Package._PrivateIncludes:
1106 if not self.MetaFile.OriginalPath.Path.startswith(PackageDir):
1107 IncludesList = list(set(Package.Includes).difference(set(Package._PrivateIncludes)))
1108 for Inc in IncludesList:
1109 if Inc not in RetVal:
1110 RetVal.append(str(Inc))
1111 return RetVal
1112
1113 @cached_property
1114 def IncludePathLength(self):
1115 return sum(len(inc)+1 for inc in self.IncludePathList)
1116
1117 ## Get HII EX PCDs which maybe used by VFR
1118 #
1119 # efivarstore used by VFR may relate with HII EX PCDs
1120 # Get the variable name and GUID from efivarstore and HII EX PCD
1121 # List the HII EX PCDs in As Built INF if both name and GUID match.
1122 #
1123 # @retval list HII EX PCDs
1124 #
1125 def _GetPcdsMaybeUsedByVfr(self):
1126 if not self.SourceFileList:
1127 return []
1128
1129 NameGuids = set()
1130 for SrcFile in self.SourceFileList:
1131 if SrcFile.Ext.lower() != '.vfr':
1132 continue
1133 Vfri = os.path.join(self.OutputDir, SrcFile.BaseName + '.i')
1134 if not os.path.exists(Vfri):
1135 continue
1136 VfriFile = open(Vfri, 'r')
1137 Content = VfriFile.read()
1138 VfriFile.close()
1139 Pos = Content.find('efivarstore')
1140 while Pos != -1:
1141 #
1142 # Make sure 'efivarstore' is the start of efivarstore statement
1143 # In case of the value of 'name' (name = efivarstore) is equal to 'efivarstore'
1144 #
1145 Index = Pos - 1
1146 while Index >= 0 and Content[Index] in ' \t\r\n':
1147 Index -= 1
1148 if Index >= 0 and Content[Index] != ';':
1149 Pos = Content.find('efivarstore', Pos + len('efivarstore'))
1150 continue
1151 #
1152 # 'efivarstore' must be followed by name and guid
1153 #
1154 Name = gEfiVarStoreNamePattern.search(Content, Pos)
1155 if not Name:
1156 break
1157 Guid = gEfiVarStoreGuidPattern.search(Content, Pos)
1158 if not Guid:
1159 break
1160 NameArray = _ConvertStringToByteArray('L"' + Name.group(1) + '"')
1161 NameGuids.add((NameArray, GuidStructureStringToGuidString(Guid.group(1))))
1162 Pos = Content.find('efivarstore', Name.end())
1163 if not NameGuids:
1164 return []
1165 HiiExPcds = []
1166 for Pcd in self.PlatformInfo.Pcds.values():
1167 if Pcd.Type != TAB_PCDS_DYNAMIC_EX_HII:
1168 continue
1169 for SkuInfo in Pcd.SkuInfoList.values():
1170 Value = GuidValue(SkuInfo.VariableGuid, self.PlatformInfo.PackageList, self.MetaFile.Path)
1171 if not Value:
1172 continue
1173 Name = _ConvertStringToByteArray(SkuInfo.VariableName)
1174 Guid = GuidStructureStringToGuidString(Value)
1175 if (Name, Guid) in NameGuids and Pcd not in HiiExPcds:
1176 HiiExPcds.append(Pcd)
1177 break
1178
1179 return HiiExPcds
1180
1181 def _GenOffsetBin(self):
1182 VfrUniBaseName = {}
1183 for SourceFile in self.Module.Sources:
1184 if SourceFile.Type.upper() == ".VFR" :
1185 #
1186 # search the .map file to find the offset of vfr binary in the PE32+/TE file.
1187 #
1188 VfrUniBaseName[SourceFile.BaseName] = (SourceFile.BaseName + "Bin")
1189 elif SourceFile.Type.upper() == ".UNI" :
1190 #
1191 # search the .map file to find the offset of Uni strings binary in the PE32+/TE file.
1192 #
1193 VfrUniBaseName["UniOffsetName"] = (self.Name + "Strings")
1194
1195 if not VfrUniBaseName:
1196 return None
1197 MapFileName = os.path.join(self.OutputDir, self.Name + ".map")
1198 EfiFileName = os.path.join(self.OutputDir, self.Name + ".efi")
1199 VfrUniOffsetList = GetVariableOffset(MapFileName, EfiFileName, list(VfrUniBaseName.values()))
1200 if not VfrUniOffsetList:
1201 return None
1202
1203 OutputName = '%sOffset.bin' % self.Name
1204 UniVfrOffsetFileName = os.path.join( self.OutputDir, OutputName)
1205
1206 try:
1207 fInputfile = open(UniVfrOffsetFileName, "wb+", 0)
1208 except:
1209 EdkLogger.error("build", FILE_OPEN_FAILURE, "File open failed for %s" % UniVfrOffsetFileName, None)
1210
1211 # Use a instance of BytesIO to cache data
1212 fStringIO = BytesIO()
1213
1214 for Item in VfrUniOffsetList:
1215 if (Item[0].find("Strings") != -1):
1216 #
1217 # UNI offset in image.
1218 # GUID + Offset
1219 # { 0x8913c5e0, 0x33f6, 0x4d86, { 0x9b, 0xf1, 0x43, 0xef, 0x89, 0xfc, 0x6, 0x66 } }
1220 #
1221 UniGuid = b'\xe0\xc5\x13\x89\xf63\x86M\x9b\xf1C\xef\x89\xfc\x06f'
1222 fStringIO.write(UniGuid)
1223 UniValue = pack ('Q', int (Item[1], 16))
1224 fStringIO.write (UniValue)
1225 else:
1226 #
1227 # VFR binary offset in image.
1228 # GUID + Offset
1229 # { 0xd0bc7cb4, 0x6a47, 0x495f, { 0xaa, 0x11, 0x71, 0x7, 0x46, 0xda, 0x6, 0xa2 } };
1230 #
1231 VfrGuid = b'\xb4|\xbc\xd0Gj_I\xaa\x11q\x07F\xda\x06\xa2'
1232 fStringIO.write(VfrGuid)
1233 VfrValue = pack ('Q', int (Item[1], 16))
1234 fStringIO.write (VfrValue)
1235 #
1236 # write data into file.
1237 #
1238 try :
1239 fInputfile.write (fStringIO.getvalue())
1240 except:
1241 EdkLogger.error("build", FILE_WRITE_FAILURE, "Write data to file %s failed, please check whether the "
1242 "file been locked or using by other applications." %UniVfrOffsetFileName, None)
1243
1244 fStringIO.close ()
1245 fInputfile.close ()
1246 return OutputName
1247 @cached_property
1248 def OutputFile(self):
1249 retVal = set()
1250 OutputDir = self.OutputDir.replace('\\', '/').strip('/')
1251 DebugDir = self.DebugDir.replace('\\', '/').strip('/')
1252 for Item in self.CodaTargetList:
1253 File = Item.Target.Path.replace('\\', '/').strip('/').replace(DebugDir, '').replace(OutputDir, '').strip('/')
1254 retVal.add(File)
1255 if self.DepexGenerated:
1256 retVal.add(self.Name + '.depex')
1257
1258 Bin = self._GenOffsetBin()
1259 if Bin:
1260 retVal.add(Bin)
1261
1262 for Root, Dirs, Files in os.walk(OutputDir):
1263 for File in Files:
1264 if File.lower().endswith('.pdb'):
1265 retVal.add(File)
1266
1267 return retVal
1268
1269 ## Create AsBuilt INF file the module
1270 #
1271 def CreateAsBuiltInf(self):
1272
1273 if self.IsAsBuiltInfCreated:
1274 return
1275
1276 # Skip INF file generation for libraries
1277 if self.IsLibrary:
1278 return
1279
1280 # Skip the following code for modules with no source files
1281 if not self.SourceFileList:
1282 return
1283
1284 # Skip the following code for modules without any binary files
1285 if self.BinaryFileList:
1286 return
1287
1288 ### TODO: How to handles mixed source and binary modules
1289
1290 # Find all DynamicEx and PatchableInModule PCDs used by this module and dependent libraries
1291 # Also find all packages that the DynamicEx PCDs depend on
1292 Pcds = []
1293 PatchablePcds = []
1294 Packages = []
1295 PcdCheckList = []
1296 PcdTokenSpaceList = []
1297 for Pcd in self.ModulePcdList + self.LibraryPcdList:
1298 if Pcd.Type == TAB_PCDS_PATCHABLE_IN_MODULE:
1299 PatchablePcds.append(Pcd)
1300 PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, TAB_PCDS_PATCHABLE_IN_MODULE))
1301 elif Pcd.Type in PCD_DYNAMIC_EX_TYPE_SET:
1302 if Pcd not in Pcds:
1303 Pcds.append(Pcd)
1304 PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC_EX))
1305 PcdCheckList.append((Pcd.TokenCName, Pcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC))
1306 PcdTokenSpaceList.append(Pcd.TokenSpaceGuidCName)
1307 GuidList = OrderedDict(self.GuidList)
1308 for TokenSpace in self.GetGuidsUsedByPcd:
1309 # If token space is not referred by patch PCD or Ex PCD, remove the GUID from GUID list
1310 # The GUIDs in GUIDs section should really be the GUIDs in source INF or referred by Ex an patch PCDs
1311 if TokenSpace not in PcdTokenSpaceList and TokenSpace in GuidList:
1312 GuidList.pop(TokenSpace)
1313 CheckList = (GuidList, self.PpiList, self.ProtocolList, PcdCheckList)
1314 for Package in self.DerivedPackageList:
1315 if Package in Packages:
1316 continue
1317 BeChecked = (Package.Guids, Package.Ppis, Package.Protocols, Package.Pcds)
1318 Found = False
1319 for Index in range(len(BeChecked)):
1320 for Item in CheckList[Index]:
1321 if Item in BeChecked[Index]:
1322 Packages.append(Package)
1323 Found = True
1324 break
1325 if Found:
1326 break
1327
1328 VfrPcds = self._GetPcdsMaybeUsedByVfr()
1329 for Pkg in self.PlatformInfo.PackageList:
1330 if Pkg in Packages:
1331 continue
1332 for VfrPcd in VfrPcds:
1333 if ((VfrPcd.TokenCName, VfrPcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC_EX) in Pkg.Pcds or
1334 (VfrPcd.TokenCName, VfrPcd.TokenSpaceGuidCName, TAB_PCDS_DYNAMIC) in Pkg.Pcds):
1335 Packages.append(Pkg)
1336 break
1337
1338 ModuleType = SUP_MODULE_DXE_DRIVER if self.ModuleType == SUP_MODULE_UEFI_DRIVER and self.DepexGenerated else self.ModuleType
1339 DriverType = self.PcdIsDriver if self.PcdIsDriver else ''
1340 Guid = self.Guid
1341 MDefs = self.Module.Defines
1342
1343 AsBuiltInfDict = {
1344 'module_name' : self.Name,
1345 'module_guid' : Guid,
1346 'module_module_type' : ModuleType,
1347 'module_version_string' : [MDefs['VERSION_STRING']] if 'VERSION_STRING' in MDefs else [],
1348 'pcd_is_driver_string' : [],
1349 'module_uefi_specification_version' : [],
1350 'module_pi_specification_version' : [],
1351 'module_entry_point' : self.Module.ModuleEntryPointList,
1352 'module_unload_image' : self.Module.ModuleUnloadImageList,
1353 'module_constructor' : self.Module.ConstructorList,
1354 'module_destructor' : self.Module.DestructorList,
1355 'module_shadow' : [MDefs['SHADOW']] if 'SHADOW' in MDefs else [],
1356 'module_pci_vendor_id' : [MDefs['PCI_VENDOR_ID']] if 'PCI_VENDOR_ID' in MDefs else [],
1357 'module_pci_device_id' : [MDefs['PCI_DEVICE_ID']] if 'PCI_DEVICE_ID' in MDefs else [],
1358 'module_pci_class_code' : [MDefs['PCI_CLASS_CODE']] if 'PCI_CLASS_CODE' in MDefs else [],
1359 'module_pci_revision' : [MDefs['PCI_REVISION']] if 'PCI_REVISION' in MDefs else [],
1360 'module_build_number' : [MDefs['BUILD_NUMBER']] if 'BUILD_NUMBER' in MDefs else [],
1361 'module_spec' : [MDefs['SPEC']] if 'SPEC' in MDefs else [],
1362 'module_uefi_hii_resource_section' : [MDefs['UEFI_HII_RESOURCE_SECTION']] if 'UEFI_HII_RESOURCE_SECTION' in MDefs else [],
1363 'module_uni_file' : [MDefs['MODULE_UNI_FILE']] if 'MODULE_UNI_FILE' in MDefs else [],
1364 'module_arch' : self.Arch,
1365 'package_item' : [Package.MetaFile.File.replace('\\', '/') for Package in Packages],
1366 'binary_item' : [],
1367 'patchablepcd_item' : [],
1368 'pcd_item' : [],
1369 'protocol_item' : [],
1370 'ppi_item' : [],
1371 'guid_item' : [],
1372 'flags_item' : [],
1373 'libraryclasses_item' : []
1374 }
1375
1376 if 'MODULE_UNI_FILE' in MDefs:
1377 UNIFile = os.path.join(self.MetaFile.Dir, MDefs['MODULE_UNI_FILE'])
1378 if os.path.isfile(UNIFile):
1379 shutil.copy2(UNIFile, self.OutputDir)
1380
1381 if self.AutoGenVersion > int(gInfSpecVersion, 0):
1382 AsBuiltInfDict['module_inf_version'] = '0x%08x' % self.AutoGenVersion
1383 else:
1384 AsBuiltInfDict['module_inf_version'] = gInfSpecVersion
1385
1386 if DriverType:
1387 AsBuiltInfDict['pcd_is_driver_string'].append(DriverType)
1388
1389 if 'UEFI_SPECIFICATION_VERSION' in self.Specification:
1390 AsBuiltInfDict['module_uefi_specification_version'].append(self.Specification['UEFI_SPECIFICATION_VERSION'])
1391 if 'PI_SPECIFICATION_VERSION' in self.Specification:
1392 AsBuiltInfDict['module_pi_specification_version'].append(self.Specification['PI_SPECIFICATION_VERSION'])
1393
1394 OutputDir = self.OutputDir.replace('\\', '/').strip('/')
1395 DebugDir = self.DebugDir.replace('\\', '/').strip('/')
1396 for Item in self.CodaTargetList:
1397 File = Item.Target.Path.replace('\\', '/').strip('/').replace(DebugDir, '').replace(OutputDir, '').strip('/')
1398 if os.path.isabs(File):
1399 File = File.replace('\\', '/').strip('/').replace(OutputDir, '').strip('/')
1400 if Item.Target.Ext.lower() == '.aml':
1401 AsBuiltInfDict['binary_item'].append('ASL|' + File)
1402 elif Item.Target.Ext.lower() == '.acpi':
1403 AsBuiltInfDict['binary_item'].append('ACPI|' + File)
1404 elif Item.Target.Ext.lower() == '.efi':
1405 AsBuiltInfDict['binary_item'].append('PE32|' + self.Name + '.efi')
1406 else:
1407 AsBuiltInfDict['binary_item'].append('BIN|' + File)
1408 if not self.DepexGenerated:
1409 DepexFile = os.path.join(self.OutputDir, self.Name + '.depex')
1410 if os.path.exists(DepexFile):
1411 self.DepexGenerated = True
1412 if self.DepexGenerated:
1413 if self.ModuleType in [SUP_MODULE_PEIM]:
1414 AsBuiltInfDict['binary_item'].append('PEI_DEPEX|' + self.Name + '.depex')
1415 elif self.ModuleType in [SUP_MODULE_DXE_DRIVER, SUP_MODULE_DXE_RUNTIME_DRIVER, SUP_MODULE_DXE_SAL_DRIVER, SUP_MODULE_UEFI_DRIVER]:
1416 AsBuiltInfDict['binary_item'].append('DXE_DEPEX|' + self.Name + '.depex')
1417 elif self.ModuleType in [SUP_MODULE_DXE_SMM_DRIVER]:
1418 AsBuiltInfDict['binary_item'].append('SMM_DEPEX|' + self.Name + '.depex')
1419
1420 Bin = self._GenOffsetBin()
1421 if Bin:
1422 AsBuiltInfDict['binary_item'].append('BIN|%s' % Bin)
1423
1424 for Root, Dirs, Files in os.walk(OutputDir):
1425 for File in Files:
1426 if File.lower().endswith('.pdb'):
1427 AsBuiltInfDict['binary_item'].append('DISPOSABLE|' + File)
1428 HeaderComments = self.Module.HeaderComments
1429 StartPos = 0
1430 for Index in range(len(HeaderComments)):
1431 if HeaderComments[Index].find('@BinaryHeader') != -1:
1432 HeaderComments[Index] = HeaderComments[Index].replace('@BinaryHeader', '@file')
1433 StartPos = Index
1434 break
1435 AsBuiltInfDict['header_comments'] = '\n'.join(HeaderComments[StartPos:]).replace(':#', '://')
1436 AsBuiltInfDict['tail_comments'] = '\n'.join(self.Module.TailComments)
1437
1438 GenList = [
1439 (self.ProtocolList, self._ProtocolComments, 'protocol_item'),
1440 (self.PpiList, self._PpiComments, 'ppi_item'),
1441 (GuidList, self._GuidComments, 'guid_item')
1442 ]
1443 for Item in GenList:
1444 for CName in Item[0]:
1445 Comments = '\n '.join(Item[1][CName]) if CName in Item[1] else ''
1446 Entry = Comments + '\n ' + CName if Comments else CName
1447 AsBuiltInfDict[Item[2]].append(Entry)
1448 PatchList = parsePcdInfoFromMapFile(
1449 os.path.join(self.OutputDir, self.Name + '.map'),
1450 os.path.join(self.OutputDir, self.Name + '.efi')
1451 )
1452 if PatchList:
1453 for Pcd in PatchablePcds:
1454 TokenCName = Pcd.TokenCName
1455 for PcdItem in GlobalData.MixedPcd:
1456 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:
1457 TokenCName = PcdItem[0]
1458 break
1459 for PatchPcd in PatchList:
1460 if TokenCName == PatchPcd[0]:
1461 break
1462 else:
1463 continue
1464 PcdValue = ''
1465 if Pcd.DatumType == 'BOOLEAN':
1466 BoolValue = Pcd.DefaultValue.upper()
1467 if BoolValue == 'TRUE':
1468 Pcd.DefaultValue = '1'
1469 elif BoolValue == 'FALSE':
1470 Pcd.DefaultValue = '0'
1471
1472 if Pcd.DatumType in TAB_PCD_NUMERIC_TYPES:
1473 HexFormat = '0x%02x'
1474 if Pcd.DatumType == TAB_UINT16:
1475 HexFormat = '0x%04x'
1476 elif Pcd.DatumType == TAB_UINT32:
1477 HexFormat = '0x%08x'
1478 elif Pcd.DatumType == TAB_UINT64:
1479 HexFormat = '0x%016x'
1480 PcdValue = HexFormat % int(Pcd.DefaultValue, 0)
1481 else:
1482 if Pcd.MaxDatumSize is None or Pcd.MaxDatumSize == '':
1483 EdkLogger.error("build", AUTOGEN_ERROR,
1484 "Unknown [MaxDatumSize] of PCD [%s.%s]" % (Pcd.TokenSpaceGuidCName, TokenCName)
1485 )
1486 ArraySize = int(Pcd.MaxDatumSize, 0)
1487 PcdValue = Pcd.DefaultValue
1488 if PcdValue[0] != '{':
1489 Unicode = False
1490 if PcdValue[0] == 'L':
1491 Unicode = True
1492 PcdValue = PcdValue.lstrip('L')
1493 PcdValue = eval(PcdValue)
1494 NewValue = '{'
1495 for Index in range(0, len(PcdValue)):
1496 if Unicode:
1497 CharVal = ord(PcdValue[Index])
1498 NewValue = NewValue + '0x%02x' % (CharVal & 0x00FF) + ', ' \
1499 + '0x%02x' % (CharVal >> 8) + ', '
1500 else:
1501 NewValue = NewValue + '0x%02x' % (ord(PcdValue[Index]) % 0x100) + ', '
1502 Padding = '0x00, '
1503 if Unicode:
1504 Padding = Padding * 2
1505 ArraySize = ArraySize // 2
1506 if ArraySize < (len(PcdValue) + 1):
1507 if Pcd.MaxSizeUserSet:
1508 EdkLogger.error("build", AUTOGEN_ERROR,
1509 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd.TokenSpaceGuidCName, TokenCName)
1510 )
1511 else:
1512 ArraySize = len(PcdValue) + 1
1513 if ArraySize > len(PcdValue) + 1:
1514 NewValue = NewValue + Padding * (ArraySize - len(PcdValue) - 1)
1515 PcdValue = NewValue + Padding.strip().rstrip(',') + '}'
1516 elif len(PcdValue.split(',')) <= ArraySize:
1517 PcdValue = PcdValue.rstrip('}') + ', 0x00' * (ArraySize - len(PcdValue.split(',')))
1518 PcdValue += '}'
1519 else:
1520 if Pcd.MaxSizeUserSet:
1521 EdkLogger.error("build", AUTOGEN_ERROR,
1522 "The maximum size of VOID* type PCD '%s.%s' is less than its actual size occupied." % (Pcd.TokenSpaceGuidCName, TokenCName)
1523 )
1524 else:
1525 ArraySize = len(PcdValue) + 1
1526 PcdItem = '%s.%s|%s|0x%X' % \
1527 (Pcd.TokenSpaceGuidCName, TokenCName, PcdValue, PatchPcd[1])
1528 PcdComments = ''
1529 if (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in self._PcdComments:
1530 PcdComments = '\n '.join(self._PcdComments[Pcd.TokenSpaceGuidCName, Pcd.TokenCName])
1531 if PcdComments:
1532 PcdItem = PcdComments + '\n ' + PcdItem
1533 AsBuiltInfDict['patchablepcd_item'].append(PcdItem)
1534
1535 for Pcd in Pcds + VfrPcds:
1536 PcdCommentList = []
1537 HiiInfo = ''
1538 TokenCName = Pcd.TokenCName
1539 for PcdItem in GlobalData.MixedPcd:
1540 if (Pcd.TokenCName, Pcd.TokenSpaceGuidCName) in GlobalData.MixedPcd[PcdItem]:
1541 TokenCName = PcdItem[0]
1542 break
1543 if Pcd.Type == TAB_PCDS_DYNAMIC_EX_HII:
1544 for SkuName in Pcd.SkuInfoList:
1545 SkuInfo = Pcd.SkuInfoList[SkuName]
1546 HiiInfo = '## %s|%s|%s' % (SkuInfo.VariableName, SkuInfo.VariableGuid, SkuInfo.VariableOffset)
1547 break
1548 if (Pcd.TokenSpaceGuidCName, Pcd.TokenCName) in self._PcdComments:
1549 PcdCommentList = self._PcdComments[Pcd.TokenSpaceGuidCName, Pcd.TokenCName][:]
1550 if HiiInfo:
1551 UsageIndex = -1
1552 UsageStr = ''
1553 for Index, Comment in enumerate(PcdCommentList):
1554 for Usage in UsageList:
1555 if Comment.find(Usage) != -1:
1556 UsageStr = Usage
1557 UsageIndex = Index
1558 break
1559 if UsageIndex != -1:
1560 PcdCommentList[UsageIndex] = '## %s %s %s' % (UsageStr, HiiInfo, PcdCommentList[UsageIndex].replace(UsageStr, ''))
1561 else:
1562 PcdCommentList.append('## UNDEFINED ' + HiiInfo)
1563 PcdComments = '\n '.join(PcdCommentList)
1564 PcdEntry = Pcd.TokenSpaceGuidCName + '.' + TokenCName
1565 if PcdComments:
1566 PcdEntry = PcdComments + '\n ' + PcdEntry
1567 AsBuiltInfDict['pcd_item'].append(PcdEntry)
1568 for Item in self.BuildOption:
1569 if 'FLAGS' in self.BuildOption[Item]:
1570 AsBuiltInfDict['flags_item'].append('%s:%s_%s_%s_%s_FLAGS = %s' % (self.ToolChainFamily, self.BuildTarget, self.ToolChain, self.Arch, Item, self.BuildOption[Item]['FLAGS'].strip()))
1571
1572 # Generated LibraryClasses section in comments.
1573 for Library in self.LibraryAutoGenList:
1574 AsBuiltInfDict['libraryclasses_item'].append(Library.MetaFile.File.replace('\\', '/'))
1575
1576 # Generated UserExtensions TianoCore section.
1577 # All tianocore user extensions are copied.
1578 UserExtStr = ''
1579 for TianoCore in self._GetTianoCoreUserExtensionList():
1580 UserExtStr += '\n'.join(TianoCore)
1581 ExtensionFile = os.path.join(self.MetaFile.Dir, TianoCore[1])
1582 if os.path.isfile(ExtensionFile):
1583 shutil.copy2(ExtensionFile, self.OutputDir)
1584 AsBuiltInfDict['userextension_tianocore_item'] = UserExtStr
1585
1586 # Generated depex expression section in comments.
1587 DepexExpression = self._GetDepexExpresionString()
1588 AsBuiltInfDict['depexsection_item'] = DepexExpression if DepexExpression else ''
1589
1590 AsBuiltInf = TemplateString()
1591 AsBuiltInf.Append(gAsBuiltInfHeaderString.Replace(AsBuiltInfDict))
1592
1593 SaveFileOnChange(os.path.join(self.OutputDir, self.Name + '.inf'), str(AsBuiltInf), False)
1594
1595 self.IsAsBuiltInfCreated = True
1596
1597 def CopyModuleToCache(self):
1598 FileDir = path.join(GlobalData.gBinCacheDest, self.PlatformInfo.Name, self.BuildTarget + "_" + self.ToolChain, self.Arch, self.SourceDir, self.MetaFile.BaseName)
1599 CreateDirectory (FileDir)
1600 HashFile = path.join(self.BuildDir, self.Name + '.hash')
1601 if os.path.exists(HashFile):
1602 CopyFileOnChange(HashFile, FileDir)
1603 ModuleFile = path.join(self.OutputDir, self.Name + '.inf')
1604 if os.path.exists(ModuleFile):
1605 CopyFileOnChange(ModuleFile, FileDir)
1606 if not self.OutputFile:
1607 Ma = self.BuildDatabase[self.MetaFile, self.Arch, self.BuildTarget, self.ToolChain]
1608 self.OutputFile = Ma.Binaries
1609 for File in self.OutputFile:
1610 File = str(File)
1611 if not os.path.isabs(File):
1612 File = os.path.join(self.OutputDir, File)
1613 if os.path.exists(File):
1614 sub_dir = os.path.relpath(File, self.OutputDir)
1615 destination_file = os.path.join(FileDir, sub_dir)
1616 destination_dir = os.path.dirname(destination_file)
1617 CreateDirectory(destination_dir)
1618 CopyFileOnChange(File, destination_dir)
1619
1620 def AttemptModuleCacheCopy(self):
1621 # If library or Module is binary do not skip by hash
1622 if self.IsBinaryModule:
1623 return False
1624 # .inc is contains binary information so do not skip by hash as well
1625 for f_ext in self.SourceFileList:
1626 if '.inc' in str(f_ext):
1627 return False
1628 FileDir = path.join(GlobalData.gBinCacheSource, self.PlatformInfo.Name, self.BuildTarget + "_" + self.ToolChain, self.Arch, self.SourceDir, self.MetaFile.BaseName)
1629 HashFile = path.join(FileDir, self.Name + '.hash')
1630 if os.path.exists(HashFile):
1631 f = open(HashFile, 'r')
1632 CacheHash = f.read()
1633 f.close()
1634 self.GenModuleHash()
1635 if GlobalData.gModuleHash[self.Arch][self.Name]:
1636 if CacheHash == GlobalData.gModuleHash[self.Arch][self.Name]:
1637 for root, dir, files in os.walk(FileDir):
1638 for f in files:
1639 if self.Name + '.hash' in f:
1640 CopyFileOnChange(HashFile, self.BuildDir)
1641 else:
1642 File = path.join(root, f)
1643 sub_dir = os.path.relpath(File, FileDir)
1644 destination_file = os.path.join(self.OutputDir, sub_dir)
1645 destination_dir = os.path.dirname(destination_file)
1646 CreateDirectory(destination_dir)
1647 CopyFileOnChange(File, destination_dir)
1648 if self.Name == "PcdPeim" or self.Name == "PcdDxe":
1649 CreatePcdDatabaseCode(self, TemplateString(), TemplateString())
1650 return True
1651 return False
1652
1653 ## Create makefile for the module and its dependent libraries
1654 #
1655 # @param CreateLibraryMakeFile Flag indicating if or not the makefiles of
1656 # dependent libraries will be created
1657 #
1658 @cached_class_function
1659 def CreateMakeFile(self, CreateLibraryMakeFile=True, GenFfsList = []):
1660 # nest this function inside it's only caller.
1661 def CreateTimeStamp():
1662 FileSet = {self.MetaFile.Path}
1663
1664 for SourceFile in self.Module.Sources:
1665 FileSet.add (SourceFile.Path)
1666
1667 for Lib in self.DependentLibraryList:
1668 FileSet.add (Lib.MetaFile.Path)
1669
1670 for f in self.AutoGenDepSet:
1671 FileSet.add (f.Path)
1672
1673 if os.path.exists (self.TimeStampPath):
1674 os.remove (self.TimeStampPath)
1675 with open(self.TimeStampPath, 'w+') as fd:
1676 for f in FileSet:
1677 fd.write(f)
1678 fd.write("\n")
1679
1680 # Ignore generating makefile when it is a binary module
1681 if self.IsBinaryModule:
1682 return
1683
1684 self.GenFfsList = GenFfsList
1685
1686 if not self.IsLibrary and CreateLibraryMakeFile:
1687 for LibraryAutoGen in self.LibraryAutoGenList:
1688 LibraryAutoGen.CreateMakeFile()
1689 # Don't enable if hash feature enabled, CanSkip uses timestamps to determine build skipping
1690 if not GlobalData.gUseHashCache and self.CanSkip():
1691 return
1692
1693 if len(self.CustomMakefile) == 0:
1694 Makefile = GenMake.ModuleMakefile(self)
1695 else:
1696 Makefile = GenMake.CustomMakefile(self)
1697 if Makefile.Generate():
1698 EdkLogger.debug(EdkLogger.DEBUG_9, "Generated makefile for module %s [%s]" %
1699 (self.Name, self.Arch))
1700 else:
1701 EdkLogger.debug(EdkLogger.DEBUG_9, "Skipped the generation of makefile for module %s [%s]" %
1702 (self.Name, self.Arch))
1703
1704 CreateTimeStamp()
1705
1706 def CopyBinaryFiles(self):
1707 for File in self.Module.Binaries:
1708 SrcPath = File.Path
1709 DstPath = os.path.join(self.OutputDir, os.path.basename(SrcPath))
1710 CopyLongFilePath(SrcPath, DstPath)
1711 ## Create autogen code for the module and its dependent libraries
1712 #
1713 # @param CreateLibraryCodeFile Flag indicating if or not the code of
1714 # dependent libraries will be created
1715 #
1716 def CreateCodeFile(self, CreateLibraryCodeFile=True):
1717 if self.IsCodeFileCreated:
1718 return
1719
1720 # Need to generate PcdDatabase even PcdDriver is binarymodule
1721 if self.IsBinaryModule and self.PcdIsDriver != '':
1722 CreatePcdDatabaseCode(self, TemplateString(), TemplateString())
1723 return
1724 if self.IsBinaryModule:
1725 if self.IsLibrary:
1726 self.CopyBinaryFiles()
1727 return
1728
1729 if not self.IsLibrary and CreateLibraryCodeFile:
1730 for LibraryAutoGen in self.LibraryAutoGenList:
1731 LibraryAutoGen.CreateCodeFile()
1732
1733 # Don't enable if hash feature enabled, CanSkip uses timestamps to determine build skipping
1734 if not GlobalData.gUseHashCache and self.CanSkip():
1735 return
1736
1737 AutoGenList = []
1738 IgoredAutoGenList = []
1739
1740 for File in self.AutoGenFileList:
1741 if GenC.Generate(File.Path, self.AutoGenFileList[File], File.IsBinary):
1742 AutoGenList.append(str(File))
1743 else:
1744 IgoredAutoGenList.append(str(File))
1745
1746
1747 for ModuleType in self.DepexList:
1748 # Ignore empty [depex] section or [depex] section for SUP_MODULE_USER_DEFINED module
1749 if len(self.DepexList[ModuleType]) == 0 or ModuleType == SUP_MODULE_USER_DEFINED or ModuleType == SUP_MODULE_HOST_APPLICATION:
1750 continue
1751
1752 Dpx = GenDepex.DependencyExpression(self.DepexList[ModuleType], ModuleType, True)
1753 DpxFile = gAutoGenDepexFileName % {"module_name" : self.Name}
1754
1755 if len(Dpx.PostfixNotation) != 0:
1756 self.DepexGenerated = True
1757
1758 if Dpx.Generate(path.join(self.OutputDir, DpxFile)):
1759 AutoGenList.append(str(DpxFile))
1760 else:
1761 IgoredAutoGenList.append(str(DpxFile))
1762
1763 if IgoredAutoGenList == []:
1764 EdkLogger.debug(EdkLogger.DEBUG_9, "Generated [%s] files for module %s [%s]" %
1765 (" ".join(AutoGenList), self.Name, self.Arch))
1766 elif AutoGenList == []:
1767 EdkLogger.debug(EdkLogger.DEBUG_9, "Skipped the generation of [%s] files for module %s [%s]" %
1768 (" ".join(IgoredAutoGenList), self.Name, self.Arch))
1769 else:
1770 EdkLogger.debug(EdkLogger.DEBUG_9, "Generated [%s] (skipped %s) files for module %s [%s]" %
1771 (" ".join(AutoGenList), " ".join(IgoredAutoGenList), self.Name, self.Arch))
1772
1773 self.IsCodeFileCreated = True
1774 return AutoGenList
1775
1776 ## Summarize the ModuleAutoGen objects of all libraries used by this module
1777 @cached_property
1778 def LibraryAutoGenList(self):
1779 RetVal = []
1780 for Library in self.DependentLibraryList:
1781 La = ModuleAutoGen(
1782 self.Workspace,
1783 Library.MetaFile,
1784 self.BuildTarget,
1785 self.ToolChain,
1786 self.Arch,
1787 self.PlatformInfo.MetaFile,
1788 self.DataPipe
1789 )
1790 La.IsLibrary = True
1791 if La not in RetVal:
1792 RetVal.append(La)
1793 for Lib in La.CodaTargetList:
1794 self._ApplyBuildRule(Lib.Target, TAB_UNKNOWN_FILE)
1795 return RetVal
1796
1797 def GenModuleHash(self):
1798 # Initialize a dictionary for each arch type
1799 if self.Arch not in GlobalData.gModuleHash:
1800 GlobalData.gModuleHash[self.Arch] = {}
1801
1802 # Early exit if module or library has been hashed and is in memory
1803 if self.Name in GlobalData.gModuleHash[self.Arch]:
1804 return GlobalData.gModuleHash[self.Arch][self.Name].encode('utf-8')
1805
1806 # Initialze hash object
1807 m = hashlib.md5()
1808
1809 # Add Platform level hash
1810 m.update(GlobalData.gPlatformHash.encode('utf-8'))
1811
1812 # Add Package level hash
1813 if self.DependentPackageList:
1814 for Pkg in sorted(self.DependentPackageList, key=lambda x: x.PackageName):
1815 if Pkg.PackageName in GlobalData.gPackageHash:
1816 m.update(GlobalData.gPackageHash[Pkg.PackageName].encode('utf-8'))
1817
1818 # Add Library hash
1819 if self.LibraryAutoGenList:
1820 for Lib in sorted(self.LibraryAutoGenList, key=lambda x: x.Name):
1821 if Lib.Name not in GlobalData.gModuleHash[self.Arch]:
1822 Lib.GenModuleHash()
1823 m.update(GlobalData.gModuleHash[self.Arch][Lib.Name].encode('utf-8'))
1824
1825 # Add Module self
1826 f = open(str(self.MetaFile), 'rb')
1827 Content = f.read()
1828 f.close()
1829 m.update(Content)
1830
1831 # Add Module's source files
1832 if self.SourceFileList:
1833 for File in sorted(self.SourceFileList, key=lambda x: str(x)):
1834 f = open(str(File), 'rb')
1835 Content = f.read()
1836 f.close()
1837 m.update(Content)
1838
1839 GlobalData.gModuleHash[self.Arch][self.Name] = m.hexdigest()
1840
1841 return GlobalData.gModuleHash[self.Arch][self.Name].encode('utf-8')
1842
1843 ## Decide whether we can skip the ModuleAutoGen process
1844 def CanSkipbyHash(self):
1845 # Hashing feature is off
1846 if not GlobalData.gUseHashCache:
1847 return False
1848
1849 # Initialize a dictionary for each arch type
1850 if self.Arch not in GlobalData.gBuildHashSkipTracking:
1851 GlobalData.gBuildHashSkipTracking[self.Arch] = dict()
1852
1853 # If library or Module is binary do not skip by hash
1854 if self.IsBinaryModule:
1855 return False
1856
1857 # .inc is contains binary information so do not skip by hash as well
1858 for f_ext in self.SourceFileList:
1859 if '.inc' in str(f_ext):
1860 return False
1861
1862 # Use Cache, if exists and if Module has a copy in cache
1863 if GlobalData.gBinCacheSource and self.AttemptModuleCacheCopy():
1864 return True
1865
1866 # Early exit for libraries that haven't yet finished building
1867 HashFile = path.join(self.BuildDir, self.Name + ".hash")
1868 if self.IsLibrary and not os.path.exists(HashFile):
1869 return False
1870
1871 # Return a Boolean based on if can skip by hash, either from memory or from IO.
1872 if self.Name not in GlobalData.gBuildHashSkipTracking[self.Arch]:
1873 # If hashes are the same, SaveFileOnChange() will return False.
1874 GlobalData.gBuildHashSkipTracking[self.Arch][self.Name] = not SaveFileOnChange(HashFile, self.GenModuleHash(), True)
1875 return GlobalData.gBuildHashSkipTracking[self.Arch][self.Name]
1876 else:
1877 return GlobalData.gBuildHashSkipTracking[self.Arch][self.Name]
1878
1879 ## Decide whether we can skip the ModuleAutoGen process
1880 # If any source file is newer than the module than we cannot skip
1881 #
1882 def CanSkip(self):
1883 if self.MakeFileDir in GlobalData.gSikpAutoGenCache:
1884 return True
1885 if not os.path.exists(self.TimeStampPath):
1886 return False
1887 #last creation time of the module
1888 DstTimeStamp = os.stat(self.TimeStampPath)[8]
1889
1890 SrcTimeStamp = self.Workspace._SrcTimeStamp
1891 if SrcTimeStamp > DstTimeStamp:
1892 return False
1893
1894 with open(self.TimeStampPath,'r') as f:
1895 for source in f:
1896 source = source.rstrip('\n')
1897 if not os.path.exists(source):
1898 return False
1899 if source not in ModuleAutoGen.TimeDict :
1900 ModuleAutoGen.TimeDict[source] = os.stat(source)[8]
1901 if ModuleAutoGen.TimeDict[source] > DstTimeStamp:
1902 return False
1903 GlobalData.gSikpAutoGenCache.add(self.MakeFileDir)
1904 return True
1905
1906 @cached_property
1907 def TimeStampPath(self):
1908 return os.path.join(self.MakeFileDir, 'AutoGenTimeStamp')