2 # Create makefile for MS nmake and GNU make
4 # Copyright (c) 2007 - 2017, Intel Corporation. All rights reserved.<BR>
5 # This program and the accompanying materials
6 # are licensed and made available under the terms and conditions of the BSD License
7 # which accompanies this distribution. The full text of the license may be found at
8 # http://opensource.org/licenses/bsd-license.php
10 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
16 import Common
.LongFilePathOs
as os
20 import os
.path
as path
21 from Common
.LongFilePathSupport
import OpenLongFilePath
as open
22 from Common
.MultipleWorkspace
import MultipleWorkspace
as mws
23 from Common
.BuildToolError
import *
24 from Common
.Misc
import *
25 from Common
.String
import *
26 from BuildEngine
import *
27 import Common
.GlobalData
as GlobalData
29 ## Regular expression for finding header file inclusions
30 gIncludePattern
= re
.compile(r
"^[ \t]*#?[ \t]*include(?:[ \t]*(?:\\(?:\r\n|\r|\n))*[ \t]*)*(?:\(?[\"<]?
[ \t]*)([-\w
.\\/() \t]+)(?
:[ \t]*[\">]?\
)?
)", re.MULTILINE | re.UNICODE | re.IGNORECASE)
32 ## Regular expression for matching macro used in header file inclusion
33 gMacroPattern = re.compile("([_A
-Z
][_A
-Z0
-9]*)[ \t]*\
((.+)\
)", re.UNICODE)
37 ## pattern for include style in Edk.x code
38 gProtocolDefinition = "Protocol
/%(HeaderKey)s/%(HeaderKey)s.h
"
39 gGuidDefinition = "Guid
/%(HeaderKey)s/%(HeaderKey)s.h
"
40 gArchProtocolDefinition = "ArchProtocol
/%(HeaderKey)s/%(HeaderKey)s.h
"
41 gPpiDefinition = "Ppi
/%(HeaderKey)s/%(HeaderKey)s.h
"
42 gIncludeMacroConversion = {
43 "EFI_PROTOCOL_DEFINITION
" : gProtocolDefinition,
44 "EFI_GUID_DEFINITION
" : gGuidDefinition,
45 "EFI_ARCH_PROTOCOL_DEFINITION
" : gArchProtocolDefinition,
46 "EFI_PROTOCOL_PRODUCER
" : gProtocolDefinition,
47 "EFI_PROTOCOL_CONSUMER
" : gProtocolDefinition,
48 "EFI_PROTOCOL_DEPENDENCY
" : gProtocolDefinition,
49 "EFI_ARCH_PROTOCOL_PRODUCER
" : gArchProtocolDefinition,
50 "EFI_ARCH_PROTOCOL_CONSUMER
" : gArchProtocolDefinition,
51 "EFI_ARCH_PROTOCOL_DEPENDENCY
" : gArchProtocolDefinition,
52 "EFI_PPI_DEFINITION
" : gPpiDefinition,
53 "EFI_PPI_PRODUCER
" : gPpiDefinition,
54 "EFI_PPI_CONSUMER
" : gPpiDefinition,
55 "EFI_PPI_DEPENDENCY
" : gPpiDefinition,
58 ## default makefile type
60 if sys.platform == "win32
":
68 # This base class encapsules build file and its generation. It uses template to generate
69 # the content of build file. The content of build file will be got from AutoGen objects.
71 class BuildFile(object):
72 ## template used to generate the build file (i.e. makefile if using make)
73 _TEMPLATE_ = TemplateString('')
75 _DEFAULT_FILE_NAME_ = "Makefile
"
77 ## default file name for each type of build file
80 "gmake
" : "GNUmakefile
"
83 ## Fixed header string for makefile
84 _MAKEFILE_HEADER = '''#
86 # This file is auto-generated by build utility
94 # Auto-generated makefile for building modules, libraries or platform
98 ## Header string for each type of build file
100 "nmake
" : _MAKEFILE_HEADER % _FILE_NAME_["nmake
"],
101 "gmake
" : _MAKEFILE_HEADER % _FILE_NAME_["gmake
"]
104 ## shell commands which can be used in build file in the form of macro
105 # $(CP) copy file command
106 # $(MV) move file command
107 # $(RM) remove file command
108 # $(MD) create dir command
109 # $(RD) remove dir command
117 "RD
" : "rmdir
/s
/q
",
129 ## directory separator
135 ## directory creation template
137 "nmake
" : 'if not exist %(dir)s $(MD) %(dir)s',
138 "gmake
" : "$
(MD
) %(dir)s"
141 ## directory removal template
143 "nmake
" : 'if exist %(dir)s $(RD) %(dir)s',
144 "gmake
" : "$
(RD
) %(dir)s"
148 "nmake
" : 'if exist %(Src)s $(CP) %(Src)s %(Dst)s',
149 "gmake
" : "test
-f
%(Src)s && $
(CP
) %(Src)s %(Dst)s"
153 "nmake
" : 'if exist %(dir)s cd %(dir)s',
154 "gmake
" : "test
-e
%(dir)s && cd
%(dir)s"
158 "nmake
" : 'if exist %(file)s "$
(MAKE
)" $(MAKE_FLAGS) -f %(file)s',
159 "gmake
" : 'test -e %(file)s && "$
(MAKE
)" $(MAKE_FLAGS) -f %(file)s'
163 "nmake
" : '!INCLUDE',
167 _INC_FLAG_ = {"MSFT
" : "/I
", "GCC
" : "-I
", "INTEL
" : "-I
", "RVCT
" : "-I
"}
169 ## Constructor of BuildFile
171 # @param AutoGenObject Object of AutoGen class
173 def __init__(self, AutoGenObject):
174 self._AutoGenObject = AutoGenObject
175 self._FileType = gMakeType
179 # @param FileType Type of build file. Only nmake and gmake are supported now.
181 # @retval TRUE The build file is created or re-created successfully
182 # @retval FALSE The build file exists and is the same as the one to be generated
184 def Generate(self, FileType=gMakeType):
185 if FileType not in self._FILE_NAME_:
186 EdkLogger.error("build
", PARAMETER_INVALID, "Invalid build
type [%s]" % FileType,
187 ExtraData="[%s]" % str(self._AutoGenObject))
188 self._FileType = FileType
189 FileContent = self._TEMPLATE_.Replace(self._TemplateDict)
190 FileName = self._FILE_NAME_[FileType]
191 return SaveFileOnChange(os.path.join(self._AutoGenObject.MakeFileDir, FileName), FileContent, False)
193 ## Return a list of directory creation command string
195 # @param DirList The list of directory to be created
197 # @retval list The directory creation command list
199 def GetCreateDirectoryCommand(self, DirList):
200 return [self._MD_TEMPLATE_[self._FileType] % {'dir':Dir} for Dir in DirList]
202 ## Return a list of directory removal command string
204 # @param DirList The list of directory to be removed
206 # @retval list The directory removal command list
208 def GetRemoveDirectoryCommand(self, DirList):
209 return [self._RD_TEMPLATE_[self._FileType] % {'dir':Dir} for Dir in DirList]
211 def PlaceMacro(self, Path, MacroDefinitions={}):
212 if Path.startswith("$
("):
215 PathLength = len(Path)
216 for MacroName in MacroDefinitions:
217 MacroValue = MacroDefinitions[MacroName]
218 MacroValueLength = len(MacroValue)
219 if MacroValueLength == 0:
221 if MacroValueLength <= PathLength and Path.startswith(MacroValue):
222 Path = "$
(%s)%s" % (MacroName, Path[MacroValueLength:])
226 ## ModuleMakefile class
228 # This class encapsules makefie and its generation for module. It uses template to generate
229 # the content of makefile. The content of makefile will be got from ModuleAutoGen object.
231 class ModuleMakefile(BuildFile):
232 ## template used to generate the makefile for module
233 _TEMPLATE_ = TemplateString('''\
237 # Platform Macro Definition
239 PLATFORM_NAME = ${platform_name}
240 PLATFORM_GUID = ${platform_guid}
241 PLATFORM_VERSION = ${platform_version}
242 PLATFORM_RELATIVE_DIR = ${platform_relative_directory}
243 PLATFORM_DIR = ${platform_dir}
244 PLATFORM_OUTPUT_DIR = ${platform_output_directory}
247 # Module Macro Definition
249 MODULE_NAME = ${module_name}
250 MODULE_GUID = ${module_guid}
251 MODULE_NAME_GUID = ${module_name_guid}
252 MODULE_VERSION = ${module_version}
253 MODULE_TYPE = ${module_type}
254 MODULE_FILE = ${module_file}
255 MODULE_FILE_BASE_NAME = ${module_file_base_name}
256 BASE_NAME = $(MODULE_NAME)
257 MODULE_RELATIVE_DIR = ${module_relative_directory}
258 PACKAGE_RELATIVE_DIR = ${package_relative_directory}
259 MODULE_DIR = ${module_dir}
260 FFS_OUTPUT_DIR = ${ffs_output_directory}
262 MODULE_ENTRY_POINT = ${module_entry_point}
263 ARCH_ENTRY_POINT = ${arch_entry_point}
264 IMAGE_ENTRY_POINT = ${image_entry_point}
266 ${BEGIN}${module_extra_defines}
269 # Build Configuration Macro Definition
271 ARCH = ${architecture}
272 TOOLCHAIN = ${toolchain_tag}
273 TOOLCHAIN_TAG = ${toolchain_tag}
274 TARGET = ${build_target}
277 # Build Directory Macro Definition
279 # PLATFORM_BUILD_DIR = ${platform_build_directory}
280 BUILD_DIR = ${platform_build_directory}
281 BIN_DIR = $(BUILD_DIR)${separator}${architecture}
283 MODULE_BUILD_DIR = ${module_build_directory}
284 OUTPUT_DIR = ${module_output_directory}
285 DEBUG_DIR = ${module_debug_directory}
286 DEST_DIR_OUTPUT = $(OUTPUT_DIR)
287 DEST_DIR_DEBUG = $(DEBUG_DIR)
290 # Shell Command Macro
292 ${BEGIN}${shell_command_code} = ${shell_command}
296 # Tools definitions specific to this module
298 ${BEGIN}${module_tool_definitions}
300 MAKE_FILE = ${makefile_path}
305 ${BEGIN}${file_macro}
308 COMMON_DEPS = ${BEGIN}${common_dependency_file} \\
312 # Overridable Target Macro Definitions
314 FORCE_REBUILD = force_build
317 BC_TARGET = ${BEGIN}${backward_compatible_target} ${END}
318 CODA_TARGET = ${BEGIN}${remaining_build_target} \\
322 # Default target, which will build dependent libraries in addition to source files
329 # Target used when called from platform makefile, which will bypass the build of dependent libraries
332 pbuild: $(INIT_TARGET) $(BC_TARGET) $(PCH_TARGET) $(CODA_TARGET)
338 mbuild: $(INIT_TARGET) $(BC_TARGET) gen_libs $(PCH_TARGET) $(CODA_TARGET)
341 # Build Target used in multi-thread build mode, which will bypass the init and gen_libs targets
344 tbuild: $(BC_TARGET) $(PCH_TARGET) $(CODA_TARGET)
347 # Phony target which is used to force executing commands for a target
353 # Target to update the FD
359 # Initialization target: print build information and create necessary directories
364 \t-@echo Building ... $(MODULE_DIR)${separator}$(MODULE_FILE) [$(ARCH)]
367 ${BEGIN}\t-@${create_directory_command}\n${END}
370 \t-@$(CP) $(DEBUG_DIR)${separator}AutoGen.h $(DEBUG_DIR)${separator}$(MODULE_NAME)StrDefs.h
376 \t${BEGIN}@"$
(MAKE
)" $(MAKE_FLAGS) -f ${dependent_library_build_directory}${separator}${makefile_name}
377 \t${END}@cd $(MODULE_BUILD_DIR)
380 # Build Flash Device Image
383 \t@"$
(MAKE
)" $(MAKE_FLAGS) -f $(BUILD_DIR)${separator}${makefile_name} fds
384 \t@cd $(MODULE_BUILD_DIR)
387 # Individual Object Build Targets
389 ${BEGIN}${file_build_target}
393 # clean all intermediate files
396 \t${BEGIN}${clean_command}
397 \t${END}\t$(RM) AutoGenTimeStamp
400 # clean all generated files
403 ${BEGIN}\t${cleanall_command}
404 ${END}\t$(RM) *.pdb *.idb > NUL 2>&1
405 \t$(RM) $(BIN_DIR)${separator}$(MODULE_NAME).efi
406 \t$(RM) AutoGenTimeStamp
409 # clean all dependent libraries built
412 \t${BEGIN}-@${library_build_command} cleanall
413 \t${END}@cd $(MODULE_BUILD_DIR)\n\n''')
415 _FILE_MACRO_TEMPLATE = TemplateString("${macro_name}
= ${BEGIN}
\\\n ${source_file}${END}
\n")
416 _BUILD_TARGET_TEMPLATE = TemplateString("${BEGIN}${target}
: ${deps}
\n${END}
\t${cmd}
\n")
418 ## Constructor of ModuleMakefile
420 # @param ModuleAutoGen Object of ModuleAutoGen class
422 def __init__(self, ModuleAutoGen):
423 BuildFile.__init__(self, ModuleAutoGen)
424 self.PlatformInfo = self._AutoGenObject.PlatformInfo
426 self.ResultFileList = []
427 self.IntermediateDirectoryList = ["$
(DEBUG_DIR
)", "$
(OUTPUT_DIR
)"]
429 self.SourceFileDatabase = {} # {file type : file path}
430 self.DestFileDatabase = {} # {file type : file path}
431 self.FileBuildTargetList = [] # [(src, target string)]
432 self.BuildTargetList = [] # [target string]
433 self.PendingBuildTargetList = [] # [FileBuildRule objects]
434 self.CommonFileDependency = []
435 self.FileListMacros = {}
436 self.ListFileMacros = {}
439 self.FileDependency = []
440 self.LibraryBuildCommandList = []
441 self.LibraryFileList = []
442 self.LibraryMakefileList = []
443 self.LibraryBuildDirectoryList = []
444 self.SystemLibraryList = []
445 self.Macros = sdict()
446 self.Macros["OUTPUT_DIR
" ] = self._AutoGenObject.Macros["OUTPUT_DIR
"]
447 self.Macros["DEBUG_DIR
" ] = self._AutoGenObject.Macros["DEBUG_DIR
"]
448 self.Macros["MODULE_BUILD_DIR
"] = self._AutoGenObject.Macros["MODULE_BUILD_DIR
"]
449 self.Macros["BIN_DIR
" ] = self._AutoGenObject.Macros["BIN_DIR
"]
450 self.Macros["BUILD_DIR
" ] = self._AutoGenObject.Macros["BUILD_DIR
"]
451 self.Macros["WORKSPACE
" ] = self._AutoGenObject.Macros["WORKSPACE
"]
452 self.Macros["FFS_OUTPUT_DIR
" ] = self._AutoGenObject.Macros["FFS_OUTPUT_DIR
"]
453 self.GenFfsList = ModuleAutoGen.GenFfsList
454 self.MacroList = ['FFS_OUTPUT_DIR', 'MODULE_GUID', 'OUTPUT_DIR']
455 self.FfsOutputFileList = []
457 # Compose a dict object containing information used to do replacement in template
458 def _CreateTemplateDict(self):
459 if self._FileType not in self._SEP_:
460 EdkLogger.error("build
", PARAMETER_INVALID, "Invalid Makefile
type [%s]" % self._FileType,
461 ExtraData="[%s]" % str(self._AutoGenObject))
462 Separator = self._SEP_[self._FileType]
464 # break build if no source files and binary files are found
465 if len(self._AutoGenObject.SourceFileList) == 0 and len(self._AutoGenObject.BinaryFileList) == 0:
466 EdkLogger.error("build
", AUTOGEN_ERROR, "No files to be built
in module
[%s, %s, %s]"
467 % (self._AutoGenObject.BuildTarget, self._AutoGenObject.ToolChain, self._AutoGenObject.Arch),
468 ExtraData="[%s]" % str(self._AutoGenObject))
470 # convert dependent libraries to build command
471 self.ProcessDependentLibrary()
472 if len(self._AutoGenObject.Module.ModuleEntryPointList) > 0:
473 ModuleEntryPoint = self._AutoGenObject.Module.ModuleEntryPointList[0]
475 ModuleEntryPoint = "_ModuleEntryPoint
"
477 # Intel EBC compiler enforces EfiMain
478 if self._AutoGenObject.AutoGenVersion < 0x00010005 and self._AutoGenObject.Arch == "EBC
":
479 ArchEntryPoint = "EfiMain
"
481 ArchEntryPoint = ModuleEntryPoint
483 if self._AutoGenObject.Arch == "EBC
":
484 # EBC compiler always use "EfiStart
" as entry point. Only applies to EdkII modules
485 ImageEntryPoint = "EfiStart
"
486 elif self._AutoGenObject.AutoGenVersion < 0x00010005:
487 # Edk modules use entry point specified in INF file
488 ImageEntryPoint = ModuleEntryPoint
490 # EdkII modules always use "_ModuleEntryPoint
" as entry point
491 ImageEntryPoint = "_ModuleEntryPoint
"
493 for k, v in self._AutoGenObject.Module.Defines.iteritems():
494 if k not in self._AutoGenObject.Macros.keys():
495 self._AutoGenObject.Macros[k] = v
497 if 'MODULE_ENTRY_POINT' not in self._AutoGenObject.Macros.keys():
498 self._AutoGenObject.Macros['MODULE_ENTRY_POINT'] = ModuleEntryPoint
499 if 'ARCH_ENTRY_POINT' not in self._AutoGenObject.Macros.keys():
500 self._AutoGenObject.Macros['ARCH_ENTRY_POINT'] = ArchEntryPoint
501 if 'IMAGE_ENTRY_POINT' not in self._AutoGenObject.Macros.keys():
502 self._AutoGenObject.Macros['IMAGE_ENTRY_POINT'] = ImageEntryPoint
504 PCI_COMPRESS_Flag = False
505 for k, v in self._AutoGenObject.Module.Defines.iteritems():
506 if 'PCI_COMPRESS' == k and 'TRUE' == v:
507 PCI_COMPRESS_Flag = True
511 IncPrefix = self._INC_FLAG_[self._AutoGenObject.ToolChainFamily]
512 for Tool in self._AutoGenObject.BuildOption:
513 for Attr in self._AutoGenObject.BuildOption[Tool]:
514 Value = self._AutoGenObject.BuildOption[Tool][Attr]
518 ToolsDef.append("%s = %s" % (Tool, Value))
520 # Don't generate MAKE_FLAGS in makefile. It's put in environment variable.
523 # Remove duplicated include path, if any
525 Value = RemoveDupOption(Value, IncPrefix, self._AutoGenObject.IncludePathList)
526 if Tool == "OPTROM
" and PCI_COMPRESS_Flag:
527 ValueList = Value.split()
529 for i, v in enumerate(ValueList):
532 Value = ' '.join(ValueList)
534 ToolsDef.append("%s_%s = %s" % (Tool, Attr, Value))
537 # generate the Response file and Response flag
538 RespDict = self.CommandExceedLimit()
539 RespFileList = os.path.join(self._AutoGenObject.OutputDir, 'respfilelist.txt')
541 RespFileListContent = ''
542 for Resp in RespDict.keys():
543 RespFile = os.path.join(self._AutoGenObject.OutputDir, str(Resp).lower() + '.txt')
544 StrList = RespDict[Resp].split(' ')
549 UnexpandMacro.append(Str)
552 UnexpandMacroStr = ' '.join(UnexpandMacro)
553 NewRespStr = ' '.join(NewStr)
554 SaveFileOnChange(RespFile, NewRespStr, False)
555 ToolsDef.append("%s = %s" % (Resp, UnexpandMacroStr + ' @' + RespFile))
556 RespFileListContent += '@' + RespFile + os.linesep
557 RespFileListContent += NewRespStr + os.linesep
558 SaveFileOnChange(RespFileList, RespFileListContent, False)
560 if os.path.exists(RespFileList):
561 os.remove(RespFileList)
563 # convert source files and binary files to build targets
564 self.ResultFileList = [str(T.Target) for T in self._AutoGenObject.CodaTargetList]
565 if len(self.ResultFileList) == 0 and len(self._AutoGenObject.SourceFileList) <> 0:
566 EdkLogger.error("build
", AUTOGEN_ERROR, "Nothing to build
",
567 ExtraData="[%s]" % str(self._AutoGenObject))
569 self.ProcessBuildTargetList()
570 self.ParserGenerateFfsCmd()
572 # Generate macros used to represent input files
573 FileMacroList = [] # macro name = file list
574 for FileListMacro in self.FileListMacros:
575 FileMacro = self._FILE_MACRO_TEMPLATE.Replace(
577 "macro_name
" : FileListMacro,
578 "source_file
" : self.FileListMacros[FileListMacro]
581 FileMacroList.append(FileMacro)
583 # INC_LIST is special
586 for P in self._AutoGenObject.IncludePathList:
587 IncludePathList.append(IncPrefix + self.PlaceMacro(P, self.Macros))
588 if FileBuildRule.INC_LIST_MACRO in self.ListFileMacros:
589 self.ListFileMacros[FileBuildRule.INC_LIST_MACRO].append(IncPrefix + P)
590 FileMacro += self._FILE_MACRO_TEMPLATE.Replace(
592 "macro_name
" : "INC
",
593 "source_file
" : IncludePathList
596 FileMacroList.append(FileMacro)
598 # Generate macros used to represent files containing list of input files
599 for ListFileMacro in self.ListFileMacros:
600 ListFileName = os.path.join(self._AutoGenObject.OutputDir, "%s.lst
" % ListFileMacro.lower()[:len(ListFileMacro) - 5])
601 FileMacroList.append("%s = %s" % (ListFileMacro, ListFileName))
604 "\n".join(self.ListFileMacros[ListFileMacro]),
608 # Edk modules need <BaseName>StrDefs.h for string ID
609 #if self._AutoGenObject.AutoGenVersion < 0x00010005 and len(self._AutoGenObject.UnicodeFileList) > 0:
610 # BcTargetList = ['strdefs']
615 MakefileName = self._FILE_NAME_[self._FileType]
616 LibraryMakeCommandList = []
617 for D in self.LibraryBuildDirectoryList:
618 Command = self._MAKE_TEMPLATE_[self._FileType] % {"file":os.path.join(D, MakefileName)}
619 LibraryMakeCommandList.append(Command)
621 package_rel_dir = self._AutoGenObject.SourceDir
622 current_dir = self.Macros["WORKSPACE
"]
624 while not found and os.sep in package_rel_dir:
625 index = package_rel_dir.index(os.sep)
626 current_dir = mws.join(current_dir, package_rel_dir[:index])
627 if os.path.exists(current_dir):
628 for fl in os.listdir(current_dir):
629 if fl.endswith('.dec'):
632 package_rel_dir = package_rel_dir[index + 1:]
634 MakefileTemplateDict = {
635 "makefile_header
" : self._FILE_HEADER_[self._FileType],
636 "makefile_path
" : os.path.join("$
(MODULE_BUILD_DIR
)", MakefileName),
637 "makefile_name
" : MakefileName,
638 "platform_name
" : self.PlatformInfo.Name,
639 "platform_guid
" : self.PlatformInfo.Guid,
640 "platform_version
" : self.PlatformInfo.Version,
641 "platform_relative_directory
": self.PlatformInfo.SourceDir,
642 "platform_output_directory
" : self.PlatformInfo.OutputDir,
643 "ffs_output_directory
" : self._AutoGenObject.Macros["FFS_OUTPUT_DIR
"],
644 "platform_dir
" : self._AutoGenObject.Macros["PLATFORM_DIR
"],
646 "module_name
" : self._AutoGenObject.Name,
647 "module_guid
" : self._AutoGenObject.Guid,
648 "module_name_guid
" : self._AutoGenObject._GetUniqueBaseName(),
649 "module_version
" : self._AutoGenObject.Version,
650 "module_type
" : self._AutoGenObject.ModuleType,
651 "module_file
" : self._AutoGenObject.MetaFile.Name,
652 "module_file_base_name
" : self._AutoGenObject.MetaFile.BaseName,
653 "module_relative_directory
" : self._AutoGenObject.SourceDir,
654 "module_dir
" : mws.join (self.Macros["WORKSPACE
"], self._AutoGenObject.SourceDir),
655 "package_relative_directory
": package_rel_dir,
656 "module_extra_defines
" : ["%s = %s" % (k, v) for k, v in self._AutoGenObject.Module.Defines.iteritems()],
658 "architecture
" : self._AutoGenObject.Arch,
659 "toolchain_tag
" : self._AutoGenObject.ToolChain,
660 "build_target
" : self._AutoGenObject.BuildTarget,
662 "platform_build_directory
" : self.PlatformInfo.BuildDir,
663 "module_build_directory
" : self._AutoGenObject.BuildDir,
664 "module_output_directory
" : self._AutoGenObject.OutputDir,
665 "module_debug_directory
" : self._AutoGenObject.DebugDir,
667 "separator
" : Separator,
668 "module_tool_definitions
" : ToolsDef,
670 "shell_command_code
" : self._SHELL_CMD_[self._FileType].keys(),
671 "shell_command
" : self._SHELL_CMD_[self._FileType].values(),
673 "module_entry_point
" : ModuleEntryPoint,
674 "image_entry_point
" : ImageEntryPoint,
675 "arch_entry_point
" : ArchEntryPoint,
676 "remaining_build_target
" : self.ResultFileList,
677 "common_dependency_file
" : self.CommonFileDependency,
678 "create_directory_command
" : self.GetCreateDirectoryCommand(self.IntermediateDirectoryList),
679 "clean_command
" : self.GetRemoveDirectoryCommand(["$
(OUTPUT_DIR
)"]),
680 "cleanall_command
" : self.GetRemoveDirectoryCommand(["$
(DEBUG_DIR
)", "$
(OUTPUT_DIR
)"]),
681 "dependent_library_build_directory
" : self.LibraryBuildDirectoryList,
682 "library_build_command
" : LibraryMakeCommandList,
683 "file_macro
" : FileMacroList,
684 "file_build_target
" : self.BuildTargetList,
685 "backward_compatible_target
": BcTargetList,
688 return MakefileTemplateDict
690 def ParserGenerateFfsCmd(self):
691 #Add Ffs cmd to self.BuildTargetList
695 for Cmd in self.GenFfsList:
697 for CopyCmd in Cmd[2]:
699 Src = self.ReplaceMacro(Src)
700 Dst = self.ReplaceMacro(Dst)
701 if Dst not in self.ResultFileList:
702 self.ResultFileList.append('%s' % Dst)
703 if '%s :' %(Dst) not in self.BuildTargetList:
704 self.BuildTargetList.append("%s :" %(Dst))
705 self.BuildTargetList.append('\t' + self._CP_TEMPLATE_[self._FileType] %{'Src': Src, 'Dst': Dst})
708 for index, Str in enumerate(FfsCmdList):
710 OutputFile = FfsCmdList[index + 1]
712 if DepsFileList == []:
713 DepsFileList = [FfsCmdList[index + 1]]
715 DepsFileList.append(FfsCmdList[index + 1])
716 DepsFileString = ' '.join(DepsFileList).strip()
717 if DepsFileString == '':
719 OutputFile = self.ReplaceMacro(OutputFile)
720 self.ResultFileList.append('%s' % OutputFile)
721 DepsFileString = self.ReplaceMacro(DepsFileString)
722 self.BuildTargetList.append('%s : %s' % (OutputFile, DepsFileString))
723 CmdString = ' '.join(FfsCmdList).strip()
724 CmdString = self.ReplaceMacro(CmdString)
725 self.BuildTargetList.append('\t%s' % CmdString)
727 self.ParseSecCmd(DepsFileList, Cmd[1])
728 for SecOutputFile, SecDepsFile, SecCmd in self.FfsOutputFileList :
729 self.BuildTargetList.append('%s : %s' % (self.ReplaceMacro(SecOutputFile), self.ReplaceMacro(SecDepsFile)))
730 self.BuildTargetList.append('\t%s' % self.ReplaceMacro(SecCmd))
731 self.FfsOutputFileList = []
733 def ParseSecCmd(self, OutputFileList, CmdTuple):
734 for OutputFile in OutputFileList:
735 for SecCmdStr in CmdTuple:
737 SecCmdList = SecCmdStr.split()
738 CmdName = SecCmdList[0]
739 for index, CmdItem in enumerate(SecCmdList):
740 if '-o' == CmdItem and OutputFile == SecCmdList[index + 1]:
742 while index + 1 < len(SecCmdList):
743 if not SecCmdList[index+1].startswith('-'):
744 SecDepsFileList.append(SecCmdList[index + 1])
746 if CmdName == 'Trim':
747 SecDepsFileList.append(os.path.join('$(DEBUG_DIR)', os.path.basename(OutputFile).replace('offset', 'efi')))
748 if OutputFile.endswith('.ui') or OutputFile.endswith('.ver'):
749 SecDepsFileList.append(os.path.join('$(MODULE_DIR)','$(MODULE_FILE)'))
750 self.FfsOutputFileList.append((OutputFile, ' '.join(SecDepsFileList), SecCmdStr))
751 if len(SecDepsFileList) > 0:
752 self.ParseSecCmd(SecDepsFileList, CmdTuple)
757 def ReplaceMacro(self, str):
758 for Macro in self.MacroList:
759 if self._AutoGenObject.Macros[Macro] and self._AutoGenObject.Macros[Macro] in str:
760 str = str.replace(self._AutoGenObject.Macros[Macro], '$(' + Macro + ')')
763 def CommandExceedLimit(self):
765 'CC' : { 'Macro' : '$(CC_FLAGS)', 'Value' : False},
766 'PP' : { 'Macro' : '$(PP_FLAGS)', 'Value' : False},
767 'APP' : { 'Macro' : '$(APP_FLAGS)', 'Value' : False},
768 'ASLPP' : { 'Macro' : '$(ASLPP_FLAGS)', 'Value' : False},
769 'VFRPP' : { 'Macro' : '$(VFRPP_FLAGS)', 'Value' : False},
770 'ASM' : { 'Macro' : '$(ASM_FLAGS)', 'Value' : False},
771 'ASLCC' : { 'Macro' : '$(ASLCC_FLAGS)', 'Value' : False},
776 IncPrefix = self._INC_FLAG_[self._AutoGenObject.ToolChainFamily]
778 # base on the source files to decide the file type
779 for File in self._AutoGenObject.SourceFileList:
780 for type in self._AutoGenObject.FileTypes:
781 if File in self._AutoGenObject.FileTypes[type]:
782 if type not in FileTypeList:
783 FileTypeList.append(type)
785 # calculate the command-line length
787 for type in FileTypeList:
788 BuildTargets = self._AutoGenObject.BuildRules[type].BuildTargets
789 for Target in BuildTargets:
790 CommandList = BuildTargets[Target].Commands
791 for SingleCommand in CommandList:
793 SingleCommandLength = len(SingleCommand)
794 SingleCommandList = SingleCommand.split()
795 if len(SingleCommandList) > 0:
796 for Flag in FlagDict.keys():
797 if '$('+ Flag +')' in SingleCommandList[0]:
801 SingleCommandLength += len(self._AutoGenObject._BuildOption[Tool]['PATH'])
802 for item in SingleCommandList[1:]:
803 if FlagDict[Tool]['Macro'] in item:
804 Str = self._AutoGenObject._BuildOption[Tool]['FLAGS']
805 for Option in self._AutoGenObject.BuildOption.keys():
806 for Attr in self._AutoGenObject.BuildOption[Option]:
807 if Str.find(Option + '_' + Attr) != -1:
808 Str = Str.replace('$(' + Option + '_' + Attr + ')', self._AutoGenObject.BuildOption[Option][Attr])
809 while(Str.find('$(') != -1):
810 for macro in self._AutoGenObject.Macros.keys():
811 MacroName = '$('+ macro + ')'
812 if (Str.find(MacroName) != -1):
813 Str = Str.replace(MacroName, self._AutoGenObject.Macros[macro])
817 SingleCommandLength += len(Str)
818 elif '$(INC)' in item:
819 SingleCommandLength += self._AutoGenObject.IncludePathLength + len(IncPrefix) * len(self._AutoGenObject._IncludePathList)
820 elif item.find('$(') != -1:
822 for Option in self._AutoGenObject.BuildOption.keys():
823 for Attr in self._AutoGenObject.BuildOption[Option]:
824 if Str.find(Option + '_' + Attr) != -1:
825 Str = Str.replace('$(' + Option + '_' + Attr + ')', self._AutoGenObject.BuildOption[Option][Attr])
826 while(Str.find('$(') != -1):
827 for macro in self._AutoGenObject.Macros.keys():
828 MacroName = '$('+ macro + ')'
829 if (Str.find(MacroName) != -1):
830 Str = Str.replace(MacroName, self._AutoGenObject.Macros[macro])
834 SingleCommandLength += len(Str)
836 if SingleCommandLength > GlobalData.gCommandMaxLength:
837 FlagDict[Tool]['Value'] = True
839 # generate the response file content by combine the FLAGS and INC
840 for Flag in FlagDict.keys():
841 if FlagDict[Flag]['Value']:
843 RespMacro = FlagDict[Flag]['Macro'].replace('FLAGS', 'RESP')
844 Value = self._AutoGenObject.BuildOption[Flag]['FLAGS']
845 for inc in self._AutoGenObject._IncludePathList:
846 Value += ' ' + IncPrefix + inc
847 for Option in self._AutoGenObject.BuildOption.keys():
848 for Attr in self._AutoGenObject.BuildOption[Option]:
849 if Value.find(Option + '_' + Attr) != -1:
850 Value = Value.replace('$(' + Option + '_' + Attr + ')', self._AutoGenObject.BuildOption[Option][Attr])
851 while (Value.find('$(') != -1):
852 for macro in self._AutoGenObject.Macros.keys():
853 MacroName = '$('+ macro + ')'
854 if (Value.find(MacroName) != -1):
855 Value = Value.replace(MacroName, self._AutoGenObject.Macros[macro])
860 if self._AutoGenObject.ToolChainFamily == 'GCC':
861 RespDict[Key] = Value.replace('\\', '/')
863 RespDict[Key] = Value
864 for Target in BuildTargets:
865 for i, SingleCommand in enumerate(BuildTargets[Target].Commands):
866 if FlagDict[Flag]['Macro'] in SingleCommand:
867 BuildTargets[Target].Commands[i] = SingleCommand.replace('$(INC)','').replace(FlagDict[Flag]['Macro'], RespMacro)
870 def ProcessBuildTargetList(self):
872 # Search dependency file list for each source file
874 ForceIncludedFile = []
875 for File in self._AutoGenObject.AutoGenFileList:
877 ForceIncludedFile.append(File)
880 for Target in self._AutoGenObject.IntroTargetList:
881 SourceFileList.extend(Target.Inputs)
882 OutPutFileList.extend(Target.Outputs)
885 for Item in OutPutFileList:
886 if Item in SourceFileList:
887 SourceFileList.remove(Item)
889 self.FileDependency = self.GetFileDependency(
892 self._AutoGenObject.IncludePathList + self._AutoGenObject.BuildOptionIncPathList
895 for File in self.FileDependency:
896 if not self.FileDependency[File]:
897 self.FileDependency[File] = ['$(FORCE_REBUILD)']
900 self._AutoGenObject.AutoGenDepSet |= set(self.FileDependency[File])
903 if File.Ext not in [".c
", ".C
"] or File.Name == "AutoGen
.c
":
906 DepSet = set(self.FileDependency[File])
908 DepSet &= set(self.FileDependency[File])
909 # in case nothing in SourceFileList
913 # Extract common files list in the dependency files
916 self.CommonFileDependency.append(self.PlaceMacro(File.Path, self.Macros))
918 for File in self.FileDependency:
920 if File.Ext not in [".c
", ".C
"] or File.Name == "AutoGen
.c
":
922 NewDepSet = set(self.FileDependency[File])
924 self.FileDependency[File] = ["$
(COMMON_DEPS
)"] + list(NewDepSet)
926 # Convert target description object to target string in makefile
927 for Type in self._AutoGenObject.Targets:
928 for T in self._AutoGenObject.Targets[Type]:
929 # Generate related macros if needed
930 if T.GenFileListMacro and T.FileListMacro not in self.FileListMacros:
931 self.FileListMacros[T.FileListMacro] = []
932 if T.GenListFile and T.ListFileMacro not in self.ListFileMacros:
933 self.ListFileMacros[T.ListFileMacro] = []
934 if T.GenIncListFile and T.IncListFileMacro not in self.ListFileMacros:
935 self.ListFileMacros[T.IncListFileMacro] = []
938 # Add force-dependencies
939 for Dep in T.Dependencies:
940 Deps.append(self.PlaceMacro(str(Dep), self.Macros))
941 # Add inclusion-dependencies
942 if len(T.Inputs) == 1 and T.Inputs[0] in self.FileDependency:
943 for F in self.FileDependency[T.Inputs[0]]:
944 Deps.append(self.PlaceMacro(str(F), self.Macros))
945 # Add source-dependencies
947 NewFile = self.PlaceMacro(str(F), self.Macros)
948 # In order to use file list macro as dependency
950 # gnu tools need forward slash path separater, even on Windows
951 self.ListFileMacros[T.ListFileMacro].append(str(F).replace ('\\', '/'))
952 self.FileListMacros[T.FileListMacro].append(NewFile)
953 elif T.GenFileListMacro:
954 self.FileListMacros[T.FileListMacro].append(NewFile)
958 # Use file list macro as dependency
959 if T.GenFileListMacro:
960 Deps.append("$
(%s)" % T.FileListMacro)
961 if Type in [TAB_OBJECT_FILE, TAB_STATIC_LIBRARY]:
962 Deps.append("$
(%s)" % T.ListFileMacro)
965 "target
" : self.PlaceMacro(T.Target.Path, self.Macros),
966 "cmd
" : "\n\t".join(T.Commands),
969 self.BuildTargetList.append(self._BUILD_TARGET_TEMPLATE.Replace(TargetDict))
971 ## For creating makefile targets for dependent libraries
972 def ProcessDependentLibrary(self):
973 for LibraryAutoGen in self._AutoGenObject.LibraryAutoGenList:
974 if not LibraryAutoGen.IsBinaryModule:
975 self.LibraryBuildDirectoryList.append(self.PlaceMacro(LibraryAutoGen.BuildDir, self.Macros))
977 ## Return a list containing source file's dependencies
979 # @param FileList The list of source files
980 # @param ForceInculeList The list of files which will be included forcely
981 # @param SearchPathList The list of search path
983 # @retval dict The mapping between source file path and its dependencies
985 def GetFileDependency(self, FileList, ForceInculeList, SearchPathList):
988 Dependency[F] = self.GetDependencyList(F, ForceInculeList, SearchPathList)
991 ## Find dependencies for one source file
993 # By searching recursively "#include" directive in file, find out all the
994 # files needed by given source file. The dependecies will be only searched
995 # in given search path list.
997 # @param File The source file
998 # @param ForceInculeList The list of files which will be included forcely
999 # @param SearchPathList The list of search path
1001 # @retval list The list of files the given source file depends on
1003 def GetDependencyList(self
, File
, ForceList
, SearchPathList
):
1004 EdkLogger
.debug(EdkLogger
.DEBUG_1
, "Try to get dependency files for %s" % File
)
1005 FileStack
= [File
] + ForceList
1006 DependencySet
= set()
1008 if self
._AutoGenObject
.Arch
not in gDependencyDatabase
:
1009 gDependencyDatabase
[self
._AutoGenObject
.Arch
] = {}
1010 DepDb
= gDependencyDatabase
[self
._AutoGenObject
.Arch
]
1012 while len(FileStack
) > 0:
1015 FullPathDependList
= []
1016 if F
in self
.FileCache
:
1017 for CacheFile
in self
.FileCache
[F
]:
1018 FullPathDependList
.append(CacheFile
)
1019 if CacheFile
not in DependencySet
:
1020 FileStack
.append(CacheFile
)
1021 DependencySet
.update(FullPathDependList
)
1024 CurrentFileDependencyList
= []
1026 CurrentFileDependencyList
= DepDb
[F
]
1029 Fd
= open(F
.Path
, 'r')
1030 except BaseException
, X
:
1031 EdkLogger
.error("build", FILE_OPEN_FAILURE
, ExtraData
=F
.Path
+ "\n\t" + str(X
))
1033 FileContent
= Fd
.read()
1035 if len(FileContent
) == 0:
1038 if FileContent
[0] == 0xff or FileContent
[0] == 0xfe:
1039 FileContent
= unicode(FileContent
, "utf-16")
1040 IncludedFileList
= gIncludePattern
.findall(FileContent
)
1042 for Inc
in IncludedFileList
:
1044 # if there's macro used to reference header file, expand it
1045 HeaderList
= gMacroPattern
.findall(Inc
)
1046 if len(HeaderList
) == 1 and len(HeaderList
[0]) == 2:
1047 HeaderType
= HeaderList
[0][0]
1048 HeaderKey
= HeaderList
[0][1]
1049 if HeaderType
in gIncludeMacroConversion
:
1050 Inc
= gIncludeMacroConversion
[HeaderType
] % {"HeaderKey" : HeaderKey
}
1052 # not known macro used in #include, always build the file by
1053 # returning a empty dependency
1054 self
.FileCache
[File
] = []
1056 Inc
= os
.path
.normpath(Inc
)
1057 CurrentFileDependencyList
.append(Inc
)
1058 DepDb
[F
] = CurrentFileDependencyList
1060 CurrentFilePath
= F
.Dir
1061 PathList
= [CurrentFilePath
] + SearchPathList
1062 for Inc
in CurrentFileDependencyList
:
1063 for SearchPath
in PathList
:
1064 FilePath
= os
.path
.join(SearchPath
, Inc
)
1065 if FilePath
in gIsFileMap
:
1066 if not gIsFileMap
[FilePath
]:
1068 # If isfile is called too many times, the performance is slow down.
1069 elif not os
.path
.isfile(FilePath
):
1070 gIsFileMap
[FilePath
] = False
1073 gIsFileMap
[FilePath
] = True
1074 FilePath
= PathClass(FilePath
)
1075 FullPathDependList
.append(FilePath
)
1076 if FilePath
not in DependencySet
:
1077 FileStack
.append(FilePath
)
1080 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "%s included by %s was not found "\
1081 "in any given path:\n\t%s" % (Inc
, F
, "\n\t".join(SearchPathList
)))
1083 self
.FileCache
[F
] = FullPathDependList
1084 DependencySet
.update(FullPathDependList
)
1086 DependencySet
.update(ForceList
)
1087 if File
in DependencySet
:
1088 DependencySet
.remove(File
)
1089 DependencyList
= list(DependencySet
) # remove duplicate ones
1091 return DependencyList
1093 _TemplateDict
= property(_CreateTemplateDict
)
1095 ## CustomMakefile class
1097 # This class encapsules makefie and its generation for module. It uses template to generate
1098 # the content of makefile. The content of makefile will be got from ModuleAutoGen object.
1100 class CustomMakefile(BuildFile
):
1101 ## template used to generate the makefile for module with custom makefile
1102 _TEMPLATE_
= TemplateString('''\
1106 # Platform Macro Definition
1108 PLATFORM_NAME = ${platform_name}
1109 PLATFORM_GUID = ${platform_guid}
1110 PLATFORM_VERSION = ${platform_version}
1111 PLATFORM_RELATIVE_DIR = ${platform_relative_directory}
1112 PLATFORM_DIR = ${platform_dir}
1113 PLATFORM_OUTPUT_DIR = ${platform_output_directory}
1116 # Module Macro Definition
1118 MODULE_NAME = ${module_name}
1119 MODULE_GUID = ${module_guid}
1120 MODULE_NAME_GUID = ${module_name_guid}
1121 MODULE_VERSION = ${module_version}
1122 MODULE_TYPE = ${module_type}
1123 MODULE_FILE = ${module_file}
1124 MODULE_FILE_BASE_NAME = ${module_file_base_name}
1125 BASE_NAME = $(MODULE_NAME)
1126 MODULE_RELATIVE_DIR = ${module_relative_directory}
1127 MODULE_DIR = ${module_dir}
1130 # Build Configuration Macro Definition
1132 ARCH = ${architecture}
1133 TOOLCHAIN = ${toolchain_tag}
1134 TOOLCHAIN_TAG = ${toolchain_tag}
1135 TARGET = ${build_target}
1138 # Build Directory Macro Definition
1140 # PLATFORM_BUILD_DIR = ${platform_build_directory}
1141 BUILD_DIR = ${platform_build_directory}
1142 BIN_DIR = $(BUILD_DIR)${separator}${architecture}
1143 LIB_DIR = $(BIN_DIR)
1144 MODULE_BUILD_DIR = ${module_build_directory}
1145 OUTPUT_DIR = ${module_output_directory}
1146 DEBUG_DIR = ${module_debug_directory}
1147 DEST_DIR_OUTPUT = $(OUTPUT_DIR)
1148 DEST_DIR_DEBUG = $(DEBUG_DIR)
1151 # Tools definitions specific to this module
1153 ${BEGIN}${module_tool_definitions}
1155 MAKE_FILE = ${makefile_path}
1158 # Shell Command Macro
1160 ${BEGIN}${shell_command_code} = ${shell_command}
1163 ${custom_makefile_content}
1166 # Target used when called from platform makefile, which will bypass the build of dependent libraries
1179 # Build Target used in multi-thread build mode, which no init target is needed
1185 # Initialization target: print build information and create necessary directories
1188 \t-@echo Building ... $(MODULE_DIR)${separator}$(MODULE_FILE) [$(ARCH)]
1189 ${BEGIN}\t-@${create_directory_command}\n${END}\
1193 ## Constructor of CustomMakefile
1195 # @param ModuleAutoGen Object of ModuleAutoGen class
1197 def __init__(self
, ModuleAutoGen
):
1198 BuildFile
.__init
__(self
, ModuleAutoGen
)
1199 self
.PlatformInfo
= self
._AutoGenObject
.PlatformInfo
1200 self
.IntermediateDirectoryList
= ["$(DEBUG_DIR)", "$(OUTPUT_DIR)"]
1202 # Compose a dict object containing information used to do replacement in template
1203 def _CreateTemplateDict(self
):
1204 Separator
= self
._SEP
_[self
._FileType
]
1205 if self
._FileType
not in self
._AutoGenObject
.CustomMakefile
:
1206 EdkLogger
.error('build', OPTION_NOT_SUPPORTED
, "No custom makefile for %s" % self
._FileType
,
1207 ExtraData
="[%s]" % str(self
._AutoGenObject
))
1208 MakefilePath
= mws
.join(
1209 self
._AutoGenObject
.WorkspaceDir
,
1210 self
._AutoGenObject
.CustomMakefile
[self
._FileType
]
1213 CustomMakefile
= open(MakefilePath
, 'r').read()
1215 EdkLogger
.error('build', FILE_OPEN_FAILURE
, File
=str(self
._AutoGenObject
),
1216 ExtraData
=self
._AutoGenObject
.CustomMakefile
[self
._FileType
])
1220 for Tool
in self
._AutoGenObject
.BuildOption
:
1221 # Don't generate MAKE_FLAGS in makefile. It's put in environment variable.
1224 for Attr
in self
._AutoGenObject
.BuildOption
[Tool
]:
1225 if Attr
== "FAMILY":
1227 elif Attr
== "PATH":
1228 ToolsDef
.append("%s = %s" % (Tool
, self
._AutoGenObject
.BuildOption
[Tool
][Attr
]))
1230 ToolsDef
.append("%s_%s = %s" % (Tool
, Attr
, self
._AutoGenObject
.BuildOption
[Tool
][Attr
]))
1233 MakefileName
= self
._FILE
_NAME
_[self
._FileType
]
1234 MakefileTemplateDict
= {
1235 "makefile_header" : self
._FILE
_HEADER
_[self
._FileType
],
1236 "makefile_path" : os
.path
.join("$(MODULE_BUILD_DIR)", MakefileName
),
1237 "platform_name" : self
.PlatformInfo
.Name
,
1238 "platform_guid" : self
.PlatformInfo
.Guid
,
1239 "platform_version" : self
.PlatformInfo
.Version
,
1240 "platform_relative_directory": self
.PlatformInfo
.SourceDir
,
1241 "platform_output_directory" : self
.PlatformInfo
.OutputDir
,
1242 "platform_dir" : self
._AutoGenObject
.Macros
["PLATFORM_DIR"],
1244 "module_name" : self
._AutoGenObject
.Name
,
1245 "module_guid" : self
._AutoGenObject
.Guid
,
1246 "module_name_guid" : self
._AutoGenObject
._GetUniqueBaseName
(),
1247 "module_version" : self
._AutoGenObject
.Version
,
1248 "module_type" : self
._AutoGenObject
.ModuleType
,
1249 "module_file" : self
._AutoGenObject
.MetaFile
,
1250 "module_file_base_name" : self
._AutoGenObject
.MetaFile
.BaseName
,
1251 "module_relative_directory" : self
._AutoGenObject
.SourceDir
,
1252 "module_dir" : mws
.join (self
._AutoGenObject
.WorkspaceDir
, self
._AutoGenObject
.SourceDir
),
1254 "architecture" : self
._AutoGenObject
.Arch
,
1255 "toolchain_tag" : self
._AutoGenObject
.ToolChain
,
1256 "build_target" : self
._AutoGenObject
.BuildTarget
,
1258 "platform_build_directory" : self
.PlatformInfo
.BuildDir
,
1259 "module_build_directory" : self
._AutoGenObject
.BuildDir
,
1260 "module_output_directory" : self
._AutoGenObject
.OutputDir
,
1261 "module_debug_directory" : self
._AutoGenObject
.DebugDir
,
1263 "separator" : Separator
,
1264 "module_tool_definitions" : ToolsDef
,
1266 "shell_command_code" : self
._SHELL
_CMD
_[self
._FileType
].keys(),
1267 "shell_command" : self
._SHELL
_CMD
_[self
._FileType
].values(),
1269 "create_directory_command" : self
.GetCreateDirectoryCommand(self
.IntermediateDirectoryList
),
1270 "custom_makefile_content" : CustomMakefile
1273 return MakefileTemplateDict
1275 _TemplateDict
= property(_CreateTemplateDict
)
1277 ## PlatformMakefile class
1279 # This class encapsules makefie and its generation for platform. It uses
1280 # template to generate the content of makefile. The content of makefile will be
1281 # got from PlatformAutoGen object.
1283 class PlatformMakefile(BuildFile
):
1284 ## template used to generate the makefile for platform
1285 _TEMPLATE_
= TemplateString('''\
1289 # Platform Macro Definition
1291 PLATFORM_NAME = ${platform_name}
1292 PLATFORM_GUID = ${platform_guid}
1293 PLATFORM_VERSION = ${platform_version}
1294 PLATFORM_FILE = ${platform_file}
1295 PLATFORM_DIR = ${platform_dir}
1296 PLATFORM_OUTPUT_DIR = ${platform_output_directory}
1299 # Build Configuration Macro Definition
1301 TOOLCHAIN = ${toolchain_tag}
1302 TOOLCHAIN_TAG = ${toolchain_tag}
1303 TARGET = ${build_target}
1306 # Build Directory Macro Definition
1308 BUILD_DIR = ${platform_build_directory}
1309 FV_DIR = ${platform_build_directory}${separator}FV
1312 # Shell Command Macro
1314 ${BEGIN}${shell_command_code} = ${shell_command}
1318 MAKE_FILE = ${makefile_path}
1323 all: init build_libraries build_modules
1326 # Initialization target: print build information and create necessary directories
1329 \t-@echo Building ... $(PLATFORM_FILE) [${build_architecture_list}]
1330 \t${BEGIN}-@${create_directory_command}
1333 # library build target
1335 libraries: init build_libraries
1338 # module build target
1340 modules: init build_libraries build_modules
1343 # Build all libraries:
1346 ${BEGIN}\t@"$(MAKE)" $(MAKE_FLAGS) -f ${library_makefile_list} pbuild
1347 ${END}\t@cd $(BUILD_DIR)
1350 # Build all modules:
1353 ${BEGIN}\t@"$(MAKE)" $(MAKE_FLAGS) -f ${module_makefile_list} pbuild
1354 ${END}\t@cd $(BUILD_DIR)
1357 # Clean intermediate files
1360 \t${BEGIN}-@${library_build_command} clean
1361 \t${END}${BEGIN}-@${module_build_command} clean
1362 \t${END}@cd $(BUILD_DIR)
1365 # Clean all generated files except to makefile
1368 ${BEGIN}\t${cleanall_command}
1372 # Clean all library files
1375 \t${BEGIN}-@${library_build_command} cleanall
1376 \t${END}@cd $(BUILD_DIR)\n
1379 ## Constructor of PlatformMakefile
1381 # @param ModuleAutoGen Object of PlatformAutoGen class
1383 def __init__(self
, PlatformAutoGen
):
1384 BuildFile
.__init
__(self
, PlatformAutoGen
)
1385 self
.ModuleBuildCommandList
= []
1386 self
.ModuleMakefileList
= []
1387 self
.IntermediateDirectoryList
= []
1388 self
.ModuleBuildDirectoryList
= []
1389 self
.LibraryBuildDirectoryList
= []
1390 self
.LibraryMakeCommandList
= []
1392 # Compose a dict object containing information used to do replacement in template
1393 def _CreateTemplateDict(self
):
1394 Separator
= self
._SEP
_[self
._FileType
]
1396 PlatformInfo
= self
._AutoGenObject
1397 if "MAKE" not in PlatformInfo
.ToolDefinition
or "PATH" not in PlatformInfo
.ToolDefinition
["MAKE"]:
1398 EdkLogger
.error("build", OPTION_MISSING
, "No MAKE command defined. Please check your tools_def.txt!",
1399 ExtraData
="[%s]" % str(self
._AutoGenObject
))
1401 self
.IntermediateDirectoryList
= ["$(BUILD_DIR)"]
1402 self
.ModuleBuildDirectoryList
= self
.GetModuleBuildDirectoryList()
1403 self
.LibraryBuildDirectoryList
= self
.GetLibraryBuildDirectoryList()
1405 MakefileName
= self
._FILE
_NAME
_[self
._FileType
]
1406 LibraryMakefileList
= []
1407 LibraryMakeCommandList
= []
1408 for D
in self
.LibraryBuildDirectoryList
:
1409 D
= self
.PlaceMacro(D
, {"BUILD_DIR":PlatformInfo
.BuildDir
})
1410 Makefile
= os
.path
.join(D
, MakefileName
)
1411 Command
= self
._MAKE
_TEMPLATE
_[self
._FileType
] % {"file":Makefile
}
1412 LibraryMakefileList
.append(Makefile
)
1413 LibraryMakeCommandList
.append(Command
)
1414 self
.LibraryMakeCommandList
= LibraryMakeCommandList
1416 ModuleMakefileList
= []
1417 ModuleMakeCommandList
= []
1418 for D
in self
.ModuleBuildDirectoryList
:
1419 D
= self
.PlaceMacro(D
, {"BUILD_DIR":PlatformInfo
.BuildDir
})
1420 Makefile
= os
.path
.join(D
, MakefileName
)
1421 Command
= self
._MAKE
_TEMPLATE
_[self
._FileType
] % {"file":Makefile
}
1422 ModuleMakefileList
.append(Makefile
)
1423 ModuleMakeCommandList
.append(Command
)
1425 MakefileTemplateDict
= {
1426 "makefile_header" : self
._FILE
_HEADER
_[self
._FileType
],
1427 "makefile_path" : os
.path
.join("$(BUILD_DIR)", MakefileName
),
1428 "make_path" : PlatformInfo
.ToolDefinition
["MAKE"]["PATH"],
1429 "makefile_name" : MakefileName
,
1430 "platform_name" : PlatformInfo
.Name
,
1431 "platform_guid" : PlatformInfo
.Guid
,
1432 "platform_version" : PlatformInfo
.Version
,
1433 "platform_file" : self
._AutoGenObject
.MetaFile
,
1434 "platform_relative_directory": PlatformInfo
.SourceDir
,
1435 "platform_output_directory" : PlatformInfo
.OutputDir
,
1436 "platform_build_directory" : PlatformInfo
.BuildDir
,
1437 "platform_dir" : self
._AutoGenObject
.Macros
["PLATFORM_DIR"],
1439 "toolchain_tag" : PlatformInfo
.ToolChain
,
1440 "build_target" : PlatformInfo
.BuildTarget
,
1441 "shell_command_code" : self
._SHELL
_CMD
_[self
._FileType
].keys(),
1442 "shell_command" : self
._SHELL
_CMD
_[self
._FileType
].values(),
1443 "build_architecture_list" : self
._AutoGenObject
.Arch
,
1444 "architecture" : self
._AutoGenObject
.Arch
,
1445 "separator" : Separator
,
1446 "create_directory_command" : self
.GetCreateDirectoryCommand(self
.IntermediateDirectoryList
),
1447 "cleanall_command" : self
.GetRemoveDirectoryCommand(self
.IntermediateDirectoryList
),
1448 "library_makefile_list" : LibraryMakefileList
,
1449 "module_makefile_list" : ModuleMakefileList
,
1450 "library_build_command" : LibraryMakeCommandList
,
1451 "module_build_command" : ModuleMakeCommandList
,
1454 return MakefileTemplateDict
1456 ## Get the root directory list for intermediate files of all modules build
1458 # @retval list The list of directory
1460 def GetModuleBuildDirectoryList(self
):
1462 for ModuleAutoGen
in self
._AutoGenObject
.ModuleAutoGenList
:
1463 if not ModuleAutoGen
.IsBinaryModule
:
1464 DirList
.append(os
.path
.join(self
._AutoGenObject
.BuildDir
, ModuleAutoGen
.BuildDir
))
1467 ## Get the root directory list for intermediate files of all libraries build
1469 # @retval list The list of directory
1471 def GetLibraryBuildDirectoryList(self
):
1473 for LibraryAutoGen
in self
._AutoGenObject
.LibraryAutoGenList
:
1474 if not LibraryAutoGen
.IsBinaryModule
:
1475 DirList
.append(os
.path
.join(self
._AutoGenObject
.BuildDir
, LibraryAutoGen
.BuildDir
))
1478 _TemplateDict
= property(_CreateTemplateDict
)
1480 ## TopLevelMakefile class
1482 # This class encapsules makefie and its generation for entrance makefile. It
1483 # uses template to generate the content of makefile. The content of makefile
1484 # will be got from WorkspaceAutoGen object.
1486 class TopLevelMakefile(BuildFile
):
1487 ## template used to generate toplevel makefile
1488 _TEMPLATE_
= TemplateString('''${BEGIN}\tGenFds -f ${fdf_file} --conf=${conf_directory} -o ${platform_build_directory} -t ${toolchain_tag} -b ${build_target} -p ${active_platform} -a ${build_architecture_list} ${extra_options}${END}${BEGIN} -r ${fd} ${END}${BEGIN} -i ${fv} ${END}${BEGIN} -C ${cap} ${END}${BEGIN} -D ${macro} ${END}''')
1490 ## Constructor of TopLevelMakefile
1492 # @param Workspace Object of WorkspaceAutoGen class
1494 def __init__(self
, Workspace
):
1495 BuildFile
.__init
__(self
, Workspace
)
1496 self
.IntermediateDirectoryList
= []
1498 # Compose a dict object containing information used to do replacement in template
1499 def _CreateTemplateDict(self
):
1500 Separator
= self
._SEP
_[self
._FileType
]
1502 # any platform autogen object is ok because we just need common information
1503 PlatformInfo
= self
._AutoGenObject
1505 if "MAKE" not in PlatformInfo
.ToolDefinition
or "PATH" not in PlatformInfo
.ToolDefinition
["MAKE"]:
1506 EdkLogger
.error("build", OPTION_MISSING
, "No MAKE command defined. Please check your tools_def.txt!",
1507 ExtraData
="[%s]" % str(self
._AutoGenObject
))
1509 for Arch
in PlatformInfo
.ArchList
:
1510 self
.IntermediateDirectoryList
.append(Separator
.join(["$(BUILD_DIR)", Arch
]))
1511 self
.IntermediateDirectoryList
.append("$(FV_DIR)")
1513 # TRICK: for not generating GenFds call in makefile if no FDF file
1515 if PlatformInfo
.FdfFile
!= None and PlatformInfo
.FdfFile
!= "":
1516 FdfFileList
= [PlatformInfo
.FdfFile
]
1517 # macros passed to GenFds
1518 MacroList
.append('"%s=%s"' % ("EFI_SOURCE", GlobalData
.gEfiSource
.replace('\\', '\\\\')))
1519 MacroList
.append('"%s=%s"' % ("EDK_SOURCE", GlobalData
.gEdkSource
.replace('\\', '\\\\')))
1521 MacroDict
.update(GlobalData
.gGlobalDefines
)
1522 MacroDict
.update(GlobalData
.gCommandLineDefines
)
1523 MacroDict
.pop("EFI_SOURCE", "dummy")
1524 MacroDict
.pop("EDK_SOURCE", "dummy")
1525 for MacroName
in MacroDict
:
1526 if MacroDict
[MacroName
] != "":
1527 MacroList
.append('"%s=%s"' % (MacroName
, MacroDict
[MacroName
].replace('\\', '\\\\')))
1529 MacroList
.append('"%s"' % MacroName
)
1533 # pass extra common options to external program called in makefile, currently GenFds.exe
1535 LogLevel
= EdkLogger
.GetLevel()
1536 if LogLevel
== EdkLogger
.VERBOSE
:
1537 ExtraOption
+= " -v"
1538 elif LogLevel
<= EdkLogger
.DEBUG_9
:
1539 ExtraOption
+= " -d %d" % (LogLevel
- 1)
1540 elif LogLevel
== EdkLogger
.QUIET
:
1541 ExtraOption
+= " -q"
1543 if GlobalData
.gCaseInsensitive
:
1544 ExtraOption
+= " -c"
1545 if GlobalData
.gEnableGenfdsMultiThread
:
1546 ExtraOption
+= " --genfds-multi-thread"
1547 if GlobalData
.gIgnoreSource
:
1548 ExtraOption
+= " --ignore-sources"
1550 if GlobalData
.BuildOptionPcd
:
1551 for index
, option
in enumerate(GlobalData
.gCommand
):
1552 if "--pcd" == option
and GlobalData
.gCommand
[index
+1]:
1553 pcdName
, pcdValue
= GlobalData
.gCommand
[index
+1].split('=')
1554 if pcdValue
.startswith('H'):
1555 pcdValue
= 'H' + '"' + pcdValue
[1:] + '"'
1556 ExtraOption
+= " --pcd " + pcdName
+ '=' + pcdValue
1557 elif pcdValue
.startswith('L'):
1558 pcdValue
= 'L' + '"' + pcdValue
[1:] + '"'
1559 ExtraOption
+= " --pcd " + pcdName
+ '=' + pcdValue
1561 ExtraOption
+= " --pcd " + GlobalData
.gCommand
[index
+1]
1563 MakefileName
= self
._FILE
_NAME
_[self
._FileType
]
1564 SubBuildCommandList
= []
1565 for A
in PlatformInfo
.ArchList
:
1566 Command
= self
._MAKE
_TEMPLATE
_[self
._FileType
] % {"file":os
.path
.join("$(BUILD_DIR)", A
, MakefileName
)}
1567 SubBuildCommandList
.append(Command
)
1569 MakefileTemplateDict
= {
1570 "makefile_header" : self
._FILE
_HEADER
_[self
._FileType
],
1571 "makefile_path" : os
.path
.join("$(BUILD_DIR)", MakefileName
),
1572 "make_path" : PlatformInfo
.ToolDefinition
["MAKE"]["PATH"],
1573 "platform_name" : PlatformInfo
.Name
,
1574 "platform_guid" : PlatformInfo
.Guid
,
1575 "platform_version" : PlatformInfo
.Version
,
1576 "platform_build_directory" : PlatformInfo
.BuildDir
,
1577 "conf_directory" : GlobalData
.gConfDirectory
,
1579 "toolchain_tag" : PlatformInfo
.ToolChain
,
1580 "build_target" : PlatformInfo
.BuildTarget
,
1581 "shell_command_code" : self
._SHELL
_CMD
_[self
._FileType
].keys(),
1582 "shell_command" : self
._SHELL
_CMD
_[self
._FileType
].values(),
1583 'arch' : list(PlatformInfo
.ArchList
),
1584 "build_architecture_list" : ','.join(PlatformInfo
.ArchList
),
1585 "separator" : Separator
,
1586 "create_directory_command" : self
.GetCreateDirectoryCommand(self
.IntermediateDirectoryList
),
1587 "cleanall_command" : self
.GetRemoveDirectoryCommand(self
.IntermediateDirectoryList
),
1588 "sub_build_command" : SubBuildCommandList
,
1589 "fdf_file" : FdfFileList
,
1590 "active_platform" : str(PlatformInfo
),
1591 "fd" : PlatformInfo
.FdTargetList
,
1592 "fv" : PlatformInfo
.FvTargetList
,
1593 "cap" : PlatformInfo
.CapTargetList
,
1594 "extra_options" : ExtraOption
,
1595 "macro" : MacroList
,
1598 return MakefileTemplateDict
1600 ## Get the root directory list for intermediate files of all modules build
1602 # @retval list The list of directory
1604 def GetModuleBuildDirectoryList(self
):
1606 for ModuleAutoGen
in self
._AutoGenObject
.ModuleAutoGenList
:
1607 if not ModuleAutoGen
.IsBinaryModule
:
1608 DirList
.append(os
.path
.join(self
._AutoGenObject
.BuildDir
, ModuleAutoGen
.BuildDir
))
1611 ## Get the root directory list for intermediate files of all libraries build
1613 # @retval list The list of directory
1615 def GetLibraryBuildDirectoryList(self
):
1617 for LibraryAutoGen
in self
._AutoGenObject
.LibraryAutoGenList
:
1618 if not LibraryAutoGen
.IsBinaryModule
:
1619 DirList
.append(os
.path
.join(self
._AutoGenObject
.BuildDir
, LibraryAutoGen
.BuildDir
))
1622 _TemplateDict
= property(_CreateTemplateDict
)
1624 # This acts like the main() function for the script, unless it is 'import'ed into another script.
1625 if __name__
== '__main__':