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 %(dir)s cd %(dir)s',
149 "gmake
" : "test
-e
%(dir)s && cd
%(dir)s"
153 "nmake
" : 'if exist %(file)s "$
(MAKE
)" $(MAKE_FLAGS) -f %(file)s',
154 "gmake
" : 'test -e %(file)s && "$
(MAKE
)" $(MAKE_FLAGS) -f %(file)s'
158 "nmake
" : '!INCLUDE',
162 _INC_FLAG_ = {"MSFT
" : "/I
", "GCC
" : "-I
", "INTEL
" : "-I
", "RVCT
" : "-I
"}
164 ## Constructor of BuildFile
166 # @param AutoGenObject Object of AutoGen class
168 def __init__(self, AutoGenObject):
169 self._AutoGenObject = AutoGenObject
170 self._FileType = gMakeType
174 # @param FileType Type of build file. Only nmake and gmake are supported now.
176 # @retval TRUE The build file is created or re-created successfully
177 # @retval FALSE The build file exists and is the same as the one to be generated
179 def Generate(self, FileType=gMakeType):
180 if FileType not in self._FILE_NAME_:
181 EdkLogger.error("build
", PARAMETER_INVALID, "Invalid build
type [%s]" % FileType,
182 ExtraData="[%s]" % str(self._AutoGenObject))
183 self._FileType = FileType
184 FileContent = self._TEMPLATE_.Replace(self._TemplateDict)
185 FileName = self._FILE_NAME_[FileType]
186 return SaveFileOnChange(os.path.join(self._AutoGenObject.MakeFileDir, FileName), FileContent, False)
188 ## Return a list of directory creation command string
190 # @param DirList The list of directory to be created
192 # @retval list The directory creation command list
194 def GetCreateDirectoryCommand(self, DirList):
195 return [self._MD_TEMPLATE_[self._FileType] % {'dir':Dir} for Dir in DirList]
197 ## Return a list of directory removal command string
199 # @param DirList The list of directory to be removed
201 # @retval list The directory removal command list
203 def GetRemoveDirectoryCommand(self, DirList):
204 return [self._RD_TEMPLATE_[self._FileType] % {'dir':Dir} for Dir in DirList]
206 def PlaceMacro(self, Path, MacroDefinitions={}):
207 if Path.startswith("$
("):
210 PathLength = len(Path)
211 for MacroName in MacroDefinitions:
212 MacroValue = MacroDefinitions[MacroName]
213 MacroValueLength = len(MacroValue)
214 if MacroValueLength <= PathLength and Path.startswith(MacroValue):
215 Path = "$
(%s)%s" % (MacroName, Path[MacroValueLength:])
219 ## ModuleMakefile class
221 # This class encapsules makefie and its generation for module. It uses template to generate
222 # the content of makefile. The content of makefile will be got from ModuleAutoGen object.
224 class ModuleMakefile(BuildFile):
225 ## template used to generate the makefile for module
226 _TEMPLATE_ = TemplateString('''\
230 # Platform Macro Definition
232 PLATFORM_NAME = ${platform_name}
233 PLATFORM_GUID = ${platform_guid}
234 PLATFORM_VERSION = ${platform_version}
235 PLATFORM_RELATIVE_DIR = ${platform_relative_directory}
236 PLATFORM_DIR = ${platform_dir}
237 PLATFORM_OUTPUT_DIR = ${platform_output_directory}
240 # Module Macro Definition
242 MODULE_NAME = ${module_name}
243 MODULE_GUID = ${module_guid}
244 MODULE_NAME_GUID = ${module_name_guid}
245 MODULE_VERSION = ${module_version}
246 MODULE_TYPE = ${module_type}
247 MODULE_FILE = ${module_file}
248 MODULE_FILE_BASE_NAME = ${module_file_base_name}
249 BASE_NAME = $(MODULE_NAME)
250 MODULE_RELATIVE_DIR = ${module_relative_directory}
251 PACKAGE_RELATIVE_DIR = ${package_relative_directory}
252 MODULE_DIR = ${module_dir}
254 MODULE_ENTRY_POINT = ${module_entry_point}
255 ARCH_ENTRY_POINT = ${arch_entry_point}
256 IMAGE_ENTRY_POINT = ${image_entry_point}
258 ${BEGIN}${module_extra_defines}
261 # Build Configuration Macro Definition
263 ARCH = ${architecture}
264 TOOLCHAIN = ${toolchain_tag}
265 TOOLCHAIN_TAG = ${toolchain_tag}
266 TARGET = ${build_target}
269 # Build Directory Macro Definition
271 # PLATFORM_BUILD_DIR = ${platform_build_directory}
272 BUILD_DIR = ${platform_build_directory}
273 BIN_DIR = $(BUILD_DIR)${separator}${architecture}
275 MODULE_BUILD_DIR = ${module_build_directory}
276 OUTPUT_DIR = ${module_output_directory}
277 DEBUG_DIR = ${module_debug_directory}
278 DEST_DIR_OUTPUT = $(OUTPUT_DIR)
279 DEST_DIR_DEBUG = $(DEBUG_DIR)
282 # Shell Command Macro
284 ${BEGIN}${shell_command_code} = ${shell_command}
288 # Tools definitions specific to this module
290 ${BEGIN}${module_tool_definitions}
292 MAKE_FILE = ${makefile_path}
297 ${BEGIN}${file_macro}
300 COMMON_DEPS = ${BEGIN}${common_dependency_file} \\
304 # Overridable Target Macro Definitions
306 FORCE_REBUILD = force_build
309 BC_TARGET = ${BEGIN}${backward_compatible_target} ${END}
310 CODA_TARGET = ${BEGIN}${remaining_build_target} \\
314 # Default target, which will build dependent libraries in addition to source files
321 # Target used when called from platform makefile, which will bypass the build of dependent libraries
324 pbuild: $(INIT_TARGET) $(BC_TARGET) $(PCH_TARGET) $(CODA_TARGET)
330 mbuild: $(INIT_TARGET) $(BC_TARGET) gen_libs $(PCH_TARGET) $(CODA_TARGET)
333 # Build Target used in multi-thread build mode, which will bypass the init and gen_libs targets
336 tbuild: $(BC_TARGET) $(PCH_TARGET) $(CODA_TARGET)
339 # Phony target which is used to force executing commands for a target
345 # Target to update the FD
351 # Initialization target: print build information and create necessary directories
356 \t-@echo Building ... $(MODULE_DIR)${separator}$(MODULE_FILE) [$(ARCH)]
359 ${BEGIN}\t-@${create_directory_command}\n${END}
362 \t-@$(CP) $(DEBUG_DIR)${separator}AutoGen.h $(DEBUG_DIR)${separator}$(MODULE_NAME)StrDefs.h
368 \t${BEGIN}@"$
(MAKE
)" $(MAKE_FLAGS) -f ${dependent_library_build_directory}${separator}${makefile_name}
369 \t${END}@cd $(MODULE_BUILD_DIR)
372 # Build Flash Device Image
375 \t@"$
(MAKE
)" $(MAKE_FLAGS) -f $(BUILD_DIR)${separator}${makefile_name} fds
376 \t@cd $(MODULE_BUILD_DIR)
379 # Individual Object Build Targets
381 ${BEGIN}${file_build_target}
385 # clean all intermediate files
388 \t${BEGIN}${clean_command}
389 \t${END}\t$(RM) AutoGenTimeStamp
392 # clean all generated files
395 ${BEGIN}\t${cleanall_command}
396 ${END}\t$(RM) *.pdb *.idb > NUL 2>&1
397 \t$(RM) $(BIN_DIR)${separator}$(MODULE_NAME).efi
398 \t$(RM) AutoGenTimeStamp
401 # clean all dependent libraries built
404 \t${BEGIN}-@${library_build_command} cleanall
405 \t${END}@cd $(MODULE_BUILD_DIR)\n\n''')
407 _FILE_MACRO_TEMPLATE = TemplateString("${macro_name}
= ${BEGIN}
\\\n ${source_file}${END}
\n")
408 _BUILD_TARGET_TEMPLATE = TemplateString("${BEGIN}${target}
: ${deps}
\n${END}
\t${cmd}
\n")
410 ## Constructor of ModuleMakefile
412 # @param ModuleAutoGen Object of ModuleAutoGen class
414 def __init__(self, ModuleAutoGen):
415 BuildFile.__init__(self, ModuleAutoGen)
416 self.PlatformInfo = self._AutoGenObject.PlatformInfo
418 self.ResultFileList = []
419 self.IntermediateDirectoryList = ["$
(DEBUG_DIR
)", "$
(OUTPUT_DIR
)"]
421 self.SourceFileDatabase = {} # {file type : file path}
422 self.DestFileDatabase = {} # {file type : file path}
423 self.FileBuildTargetList = [] # [(src, target string)]
424 self.BuildTargetList = [] # [target string]
425 self.PendingBuildTargetList = [] # [FileBuildRule objects]
426 self.CommonFileDependency = []
427 self.FileListMacros = {}
428 self.ListFileMacros = {}
431 self.FileDependency = []
432 self.LibraryBuildCommandList = []
433 self.LibraryFileList = []
434 self.LibraryMakefileList = []
435 self.LibraryBuildDirectoryList = []
436 self.SystemLibraryList = []
437 self.Macros = sdict()
438 self.Macros["OUTPUT_DIR
" ] = self._AutoGenObject.Macros["OUTPUT_DIR
"]
439 self.Macros["DEBUG_DIR
" ] = self._AutoGenObject.Macros["DEBUG_DIR
"]
440 self.Macros["MODULE_BUILD_DIR
"] = self._AutoGenObject.Macros["MODULE_BUILD_DIR
"]
441 self.Macros["BIN_DIR
" ] = self._AutoGenObject.Macros["BIN_DIR
"]
442 self.Macros["BUILD_DIR
" ] = self._AutoGenObject.Macros["BUILD_DIR
"]
443 self.Macros["WORKSPACE
" ] = self._AutoGenObject.Macros["WORKSPACE
"]
445 # Compose a dict object containing information used to do replacement in template
446 def _CreateTemplateDict(self):
447 if self._FileType not in self._SEP_:
448 EdkLogger.error("build
", PARAMETER_INVALID, "Invalid Makefile
type [%s]" % self._FileType,
449 ExtraData="[%s]" % str(self._AutoGenObject))
450 Separator = self._SEP_[self._FileType]
452 # break build if no source files and binary files are found
453 if len(self._AutoGenObject.SourceFileList) == 0 and len(self._AutoGenObject.BinaryFileList) == 0:
454 EdkLogger.error("build
", AUTOGEN_ERROR, "No files to be built
in module
[%s, %s, %s]"
455 % (self._AutoGenObject.BuildTarget, self._AutoGenObject.ToolChain, self._AutoGenObject.Arch),
456 ExtraData="[%s]" % str(self._AutoGenObject))
458 # convert dependent libraries to build command
459 self.ProcessDependentLibrary()
460 if len(self._AutoGenObject.Module.ModuleEntryPointList) > 0:
461 ModuleEntryPoint = self._AutoGenObject.Module.ModuleEntryPointList[0]
463 ModuleEntryPoint = "_ModuleEntryPoint
"
465 # Intel EBC compiler enforces EfiMain
466 if self._AutoGenObject.AutoGenVersion < 0x00010005 and self._AutoGenObject.Arch == "EBC
":
467 ArchEntryPoint = "EfiMain
"
469 ArchEntryPoint = ModuleEntryPoint
471 if self._AutoGenObject.Arch == "EBC
":
472 # EBC compiler always use "EfiStart
" as entry point. Only applies to EdkII modules
473 ImageEntryPoint = "EfiStart
"
474 elif self._AutoGenObject.AutoGenVersion < 0x00010005:
475 # Edk modules use entry point specified in INF file
476 ImageEntryPoint = ModuleEntryPoint
478 # EdkII modules always use "_ModuleEntryPoint
" as entry point
479 ImageEntryPoint = "_ModuleEntryPoint
"
481 for k, v in self._AutoGenObject.Module.Defines.iteritems():
482 if k not in self._AutoGenObject.Macros.keys():
483 self._AutoGenObject.Macros[k] = v
485 if 'MODULE_ENTRY_POINT' not in self._AutoGenObject.Macros.keys():
486 self._AutoGenObject.Macros['MODULE_ENTRY_POINT'] = ModuleEntryPoint
487 if 'ARCH_ENTRY_POINT' not in self._AutoGenObject.Macros.keys():
488 self._AutoGenObject.Macros['ARCH_ENTRY_POINT'] = ArchEntryPoint
489 if 'IMAGE_ENTRY_POINT' not in self._AutoGenObject.Macros.keys():
490 self._AutoGenObject.Macros['IMAGE_ENTRY_POINT'] = ImageEntryPoint
492 PCI_COMPRESS_Flag = False
493 for k, v in self._AutoGenObject.Module.Defines.iteritems():
494 if 'PCI_COMPRESS' == k and 'TRUE' == v:
495 PCI_COMPRESS_Flag = True
499 IncPrefix = self._INC_FLAG_[self._AutoGenObject.ToolChainFamily]
500 for Tool in self._AutoGenObject.BuildOption:
501 for Attr in self._AutoGenObject.BuildOption[Tool]:
502 Value = self._AutoGenObject.BuildOption[Tool][Attr]
506 ToolsDef.append("%s = %s" % (Tool, Value))
508 # Don't generate MAKE_FLAGS in makefile. It's put in environment variable.
511 # Remove duplicated include path, if any
513 Value = RemoveDupOption(Value, IncPrefix, self._AutoGenObject.IncludePathList)
514 if Tool == "OPTROM
" and PCI_COMPRESS_Flag:
515 ValueList = Value.split()
517 for i, v in enumerate(ValueList):
520 Value = ' '.join(ValueList)
522 ToolsDef.append("%s_%s = %s" % (Tool, Attr, Value))
525 # generate the Response file and Response flag
526 RespDict = self.CommandExceedLimit()
527 RespFileList = os.path.join(self._AutoGenObject.OutputDir, 'respfilelist.txt')
529 RespFileListContent = ''
530 for Resp in RespDict.keys():
531 RespFile = os.path.join(self._AutoGenObject.OutputDir, str(Resp).lower() + '.txt')
532 StrList = RespDict[Resp].split(' ')
537 UnexpandMacro.append(Str)
540 UnexpandMacroStr = ' '.join(UnexpandMacro)
541 NewRespStr = ' '.join(NewStr)
542 SaveFileOnChange(RespFile, NewRespStr, False)
543 ToolsDef.append("%s = %s" % (Resp, UnexpandMacroStr + ' @' + RespFile))
544 RespFileListContent += '@' + RespFile + os.linesep
545 RespFileListContent += NewRespStr + os.linesep
546 SaveFileOnChange(RespFileList, RespFileListContent, False)
548 if os.path.exists(RespFileList):
549 os.remove(RespFileList)
551 # convert source files and binary files to build targets
552 self.ResultFileList = [str(T.Target) for T in self._AutoGenObject.CodaTargetList]
553 if len(self.ResultFileList) == 0 and len(self._AutoGenObject.SourceFileList) <> 0:
554 EdkLogger.error("build
", AUTOGEN_ERROR, "Nothing to build
",
555 ExtraData="[%s]" % str(self._AutoGenObject))
557 self.ProcessBuildTargetList()
559 # Generate macros used to represent input files
560 FileMacroList = [] # macro name = file list
561 for FileListMacro in self.FileListMacros:
562 FileMacro = self._FILE_MACRO_TEMPLATE.Replace(
564 "macro_name
" : FileListMacro,
565 "source_file
" : self.FileListMacros[FileListMacro]
568 FileMacroList.append(FileMacro)
570 # INC_LIST is special
573 for P in self._AutoGenObject.IncludePathList:
574 IncludePathList.append(IncPrefix + self.PlaceMacro(P, self.Macros))
575 if FileBuildRule.INC_LIST_MACRO in self.ListFileMacros:
576 self.ListFileMacros[FileBuildRule.INC_LIST_MACRO].append(IncPrefix + P)
577 FileMacro += self._FILE_MACRO_TEMPLATE.Replace(
579 "macro_name
" : "INC
",
580 "source_file
" : IncludePathList
583 FileMacroList.append(FileMacro)
585 # Generate macros used to represent files containing list of input files
586 for ListFileMacro in self.ListFileMacros:
587 ListFileName = os.path.join(self._AutoGenObject.OutputDir, "%s.lst
" % ListFileMacro.lower()[:len(ListFileMacro) - 5])
588 FileMacroList.append("%s = %s" % (ListFileMacro, ListFileName))
591 "\n".join(self.ListFileMacros[ListFileMacro]),
595 # Edk modules need <BaseName>StrDefs.h for string ID
596 #if self._AutoGenObject.AutoGenVersion < 0x00010005 and len(self._AutoGenObject.UnicodeFileList) > 0:
597 # BcTargetList = ['strdefs']
602 MakefileName = self._FILE_NAME_[self._FileType]
603 LibraryMakeCommandList = []
604 for D in self.LibraryBuildDirectoryList:
605 Command = self._MAKE_TEMPLATE_[self._FileType] % {"file":os.path.join(D, MakefileName)}
606 LibraryMakeCommandList.append(Command)
608 package_rel_dir = self._AutoGenObject.SourceDir
609 current_dir = self.Macros["WORKSPACE
"]
611 while not found and os.sep in package_rel_dir:
612 index = package_rel_dir.index(os.sep)
613 current_dir = mws.join(current_dir, package_rel_dir[:index])
614 if os.path.exists(current_dir):
615 for fl in os.listdir(current_dir):
616 if fl.endswith('.dec'):
619 package_rel_dir = package_rel_dir[index + 1:]
621 MakefileTemplateDict = {
622 "makefile_header
" : self._FILE_HEADER_[self._FileType],
623 "makefile_path
" : os.path.join("$
(MODULE_BUILD_DIR
)", MakefileName),
624 "makefile_name
" : MakefileName,
625 "platform_name
" : self.PlatformInfo.Name,
626 "platform_guid
" : self.PlatformInfo.Guid,
627 "platform_version
" : self.PlatformInfo.Version,
628 "platform_relative_directory
": self.PlatformInfo.SourceDir,
629 "platform_output_directory
" : self.PlatformInfo.OutputDir,
630 "platform_dir
" : self._AutoGenObject.Macros["PLATFORM_DIR
"],
632 "module_name
" : self._AutoGenObject.Name,
633 "module_guid
" : self._AutoGenObject.Guid,
634 "module_name_guid
" : self._AutoGenObject._GetUniqueBaseName(),
635 "module_version
" : self._AutoGenObject.Version,
636 "module_type
" : self._AutoGenObject.ModuleType,
637 "module_file
" : self._AutoGenObject.MetaFile.Name,
638 "module_file_base_name
" : self._AutoGenObject.MetaFile.BaseName,
639 "module_relative_directory
" : self._AutoGenObject.SourceDir,
640 "module_dir
" : mws.join (self.Macros["WORKSPACE
"], self._AutoGenObject.SourceDir),
641 "package_relative_directory
": package_rel_dir,
642 "module_extra_defines
" : ["%s = %s" % (k, v) for k, v in self._AutoGenObject.Module.Defines.iteritems()],
644 "architecture
" : self._AutoGenObject.Arch,
645 "toolchain_tag
" : self._AutoGenObject.ToolChain,
646 "build_target
" : self._AutoGenObject.BuildTarget,
648 "platform_build_directory
" : self.PlatformInfo.BuildDir,
649 "module_build_directory
" : self._AutoGenObject.BuildDir,
650 "module_output_directory
" : self._AutoGenObject.OutputDir,
651 "module_debug_directory
" : self._AutoGenObject.DebugDir,
653 "separator
" : Separator,
654 "module_tool_definitions
" : ToolsDef,
656 "shell_command_code
" : self._SHELL_CMD_[self._FileType].keys(),
657 "shell_command
" : self._SHELL_CMD_[self._FileType].values(),
659 "module_entry_point
" : ModuleEntryPoint,
660 "image_entry_point
" : ImageEntryPoint,
661 "arch_entry_point
" : ArchEntryPoint,
662 "remaining_build_target
" : self.ResultFileList,
663 "common_dependency_file
" : self.CommonFileDependency,
664 "create_directory_command
" : self.GetCreateDirectoryCommand(self.IntermediateDirectoryList),
665 "clean_command
" : self.GetRemoveDirectoryCommand(["$
(OUTPUT_DIR
)"]),
666 "cleanall_command
" : self.GetRemoveDirectoryCommand(["$
(DEBUG_DIR
)", "$
(OUTPUT_DIR
)"]),
667 "dependent_library_build_directory
" : self.LibraryBuildDirectoryList,
668 "library_build_command
" : LibraryMakeCommandList,
669 "file_macro
" : FileMacroList,
670 "file_build_target
" : self.BuildTargetList,
671 "backward_compatible_target
": BcTargetList,
674 return MakefileTemplateDict
676 def CommandExceedLimit(self):
678 'CC' : { 'Macro' : '$(CC_FLAGS)', 'Value' : False},
679 'PP' : { 'Macro' : '$(PP_FLAGS)', 'Value' : False},
680 'APP' : { 'Macro' : '$(APP_FLAGS)', 'Value' : False},
681 'ASLPP' : { 'Macro' : '$(ASLPP_FLAGS)', 'Value' : False},
682 'VFRPP' : { 'Macro' : '$(VFRPP_FLAGS)', 'Value' : False},
683 'ASM' : { 'Macro' : '$(ASM_FLAGS)', 'Value' : False},
684 'ASLCC' : { 'Macro' : '$(ASLCC_FLAGS)', 'Value' : False},
689 IncPrefix = self._INC_FLAG_[self._AutoGenObject.ToolChainFamily]
691 # base on the source files to decide the file type
692 for File in self._AutoGenObject.SourceFileList:
693 for type in self._AutoGenObject.FileTypes:
694 if File in self._AutoGenObject.FileTypes[type]:
695 if type not in FileTypeList:
696 FileTypeList.append(type)
698 # calculate the command-line length
700 for type in FileTypeList:
701 BuildTargets = self._AutoGenObject.BuildRules[type].BuildTargets
702 for Target in BuildTargets:
703 CommandList = BuildTargets[Target].Commands
704 for SingleCommand in CommandList:
706 SingleCommandLength = len(SingleCommand)
707 SingleCommandList = SingleCommand.split()
708 if len(SingleCommandList) > 0:
709 for Flag in FlagDict.keys():
710 if '$('+ Flag +')' in SingleCommandList[0]:
714 SingleCommandLength += len(self._AutoGenObject._BuildOption[Tool]['PATH'])
715 for item in SingleCommandList[1:]:
716 if FlagDict[Tool]['Macro'] in item:
717 Str = self._AutoGenObject._BuildOption[Tool]['FLAGS']
718 for Option in self._AutoGenObject.BuildOption.keys():
719 for Attr in self._AutoGenObject.BuildOption[Option]:
720 if Str.find(Option + '_' + Attr) != -1:
721 Str = Str.replace('$(' + Option + '_' + Attr + ')', self._AutoGenObject.BuildOption[Option][Attr])
722 while(Str.find('$(') != -1):
723 for macro in self._AutoGenObject.Macros.keys():
724 MacroName = '$('+ macro + ')'
725 if (Str.find(MacroName) != -1):
726 Str = Str.replace(MacroName, self._AutoGenObject.Macros[macro])
730 SingleCommandLength += len(Str)
731 elif '$(INC)' in item:
732 SingleCommandLength += self._AutoGenObject.IncludePathLength + len(IncPrefix) * len(self._AutoGenObject._IncludePathList)
733 elif item.find('$(') != -1:
735 for Option in self._AutoGenObject.BuildOption.keys():
736 for Attr in self._AutoGenObject.BuildOption[Option]:
737 if Str.find(Option + '_' + Attr) != -1:
738 Str = Str.replace('$(' + Option + '_' + Attr + ')', self._AutoGenObject.BuildOption[Option][Attr])
739 while(Str.find('$(') != -1):
740 for macro in self._AutoGenObject.Macros.keys():
741 MacroName = '$('+ macro + ')'
742 if (Str.find(MacroName) != -1):
743 Str = Str.replace(MacroName, self._AutoGenObject.Macros[macro])
747 SingleCommandLength += len(Str)
749 if SingleCommandLength > GlobalData.gCommandMaxLength:
750 FlagDict[Tool]['Value'] = True
752 # generate the response file content by combine the FLAGS and INC
753 for Flag in FlagDict.keys():
754 if FlagDict[Flag]['Value']:
756 RespMacro = FlagDict[Flag]['Macro'].replace('FLAGS', 'RESP')
757 Value = self._AutoGenObject.BuildOption[Flag]['FLAGS']
758 for inc in self._AutoGenObject._IncludePathList:
759 Value += ' ' + IncPrefix + inc
760 for Option in self._AutoGenObject.BuildOption.keys():
761 for Attr in self._AutoGenObject.BuildOption[Option]:
762 if Value.find(Option + '_' + Attr) != -1:
763 Value = Value.replace('$(' + Option + '_' + Attr + ')', self._AutoGenObject.BuildOption[Option][Attr])
764 while (Value.find('$(') != -1):
765 for macro in self._AutoGenObject.Macros.keys():
766 MacroName = '$('+ macro + ')'
767 if (Value.find(MacroName) != -1):
768 Value = Value.replace(MacroName, self._AutoGenObject.Macros[macro])
773 if self._AutoGenObject.ToolChainFamily == 'GCC':
774 RespDict[Key] = Value.replace('\\', '/')
776 RespDict[Key] = Value
777 for Target in BuildTargets:
778 for i, SingleCommand in enumerate(BuildTargets[Target].Commands):
779 if FlagDict[Flag]['Macro'] in SingleCommand:
780 BuildTargets[Target].Commands[i] = SingleCommand.replace('$(INC)','').replace(FlagDict[Flag]['Macro'], RespMacro)
783 def ProcessBuildTargetList(self):
785 # Search dependency file list for each source file
787 ForceIncludedFile = []
788 for File in self._AutoGenObject.AutoGenFileList:
790 ForceIncludedFile.append(File)
792 for Target in self._AutoGenObject.IntroTargetList:
793 SourceFileList.extend(Target.Inputs)
795 self.FileDependency = self.GetFileDependency(
798 self._AutoGenObject.IncludePathList + self._AutoGenObject.BuildOptionIncPathList
801 for File in self.FileDependency:
802 if not self.FileDependency[File]:
803 self.FileDependency[File] = ['$(FORCE_REBUILD)']
806 self._AutoGenObject.AutoGenDepSet |= set(self.FileDependency[File])
809 if File.Ext not in [".c
", ".C
"] or File.Name == "AutoGen
.c
":
812 DepSet = set(self.FileDependency[File])
814 DepSet &= set(self.FileDependency[File])
815 # in case nothing in SourceFileList
819 # Extract common files list in the dependency files
822 self.CommonFileDependency.append(self.PlaceMacro(File.Path, self.Macros))
824 for File in self.FileDependency:
826 if File.Ext not in [".c
", ".C
"] or File.Name == "AutoGen
.c
":
828 NewDepSet = set(self.FileDependency[File])
830 self.FileDependency[File] = ["$
(COMMON_DEPS
)"] + list(NewDepSet)
832 # Convert target description object to target string in makefile
833 for Type in self._AutoGenObject.Targets:
834 for T in self._AutoGenObject.Targets[Type]:
835 # Generate related macros if needed
836 if T.GenFileListMacro and T.FileListMacro not in self.FileListMacros:
837 self.FileListMacros[T.FileListMacro] = []
838 if T.GenListFile and T.ListFileMacro not in self.ListFileMacros:
839 self.ListFileMacros[T.ListFileMacro] = []
840 if T.GenIncListFile and T.IncListFileMacro not in self.ListFileMacros:
841 self.ListFileMacros[T.IncListFileMacro] = []
844 # Add force-dependencies
845 for Dep in T.Dependencies:
846 Deps.append(self.PlaceMacro(str(Dep), self.Macros))
847 # Add inclusion-dependencies
848 if len(T.Inputs) == 1 and T.Inputs[0] in self.FileDependency:
849 for F in self.FileDependency[T.Inputs[0]]:
850 Deps.append(self.PlaceMacro(str(F), self.Macros))
851 # Add source-dependencies
853 NewFile = self.PlaceMacro(str(F), self.Macros)
854 # In order to use file list macro as dependency
856 # gnu tools need forward slash path separater, even on Windows
857 self.ListFileMacros[T.ListFileMacro].append(str(F).replace ('\\', '/'))
858 self.FileListMacros[T.FileListMacro].append(NewFile)
859 elif T.GenFileListMacro:
860 self.FileListMacros[T.FileListMacro].append(NewFile)
864 # Use file list macro as dependency
865 if T.GenFileListMacro:
866 Deps.append("$
(%s)" % T.FileListMacro)
869 "target
" : self.PlaceMacro(T.Target.Path, self.Macros),
870 "cmd
" : "\n\t".join(T.Commands),
873 self.BuildTargetList.append(self._BUILD_TARGET_TEMPLATE.Replace(TargetDict))
875 ## For creating makefile targets for dependent libraries
876 def ProcessDependentLibrary(self):
877 for LibraryAutoGen in self._AutoGenObject.LibraryAutoGenList:
878 if not LibraryAutoGen.IsBinaryModule:
879 self.LibraryBuildDirectoryList.append(self.PlaceMacro(LibraryAutoGen.BuildDir, self.Macros))
881 ## Return a list containing source file's dependencies
883 # @param FileList The list of source files
884 # @param ForceInculeList The list of files which will be included forcely
885 # @param SearchPathList The list of search path
887 # @retval dict The mapping between source file path and its dependencies
889 def GetFileDependency(self, FileList, ForceInculeList, SearchPathList):
892 Dependency[F] = self.GetDependencyList(F, ForceInculeList, SearchPathList)
895 ## Find dependencies for one source file
897 # By searching recursively "#include" directive in file, find out all the
898 # files needed by given source file. The dependecies will be only searched
899 # in given search path list.
901 # @param File The source file
902 # @param ForceInculeList The list of files which will be included forcely
903 # @param SearchPathList The list of search path
905 # @retval list The list of files the given source file depends on
907 def GetDependencyList(self
, File
, ForceList
, SearchPathList
):
908 EdkLogger
.debug(EdkLogger
.DEBUG_1
, "Try to get dependency files for %s" % File
)
909 FileStack
= [File
] + ForceList
910 DependencySet
= set()
912 if self
._AutoGenObject
.Arch
not in gDependencyDatabase
:
913 gDependencyDatabase
[self
._AutoGenObject
.Arch
] = {}
914 DepDb
= gDependencyDatabase
[self
._AutoGenObject
.Arch
]
916 while len(FileStack
) > 0:
919 FullPathDependList
= []
920 if F
in self
.FileCache
:
921 for CacheFile
in self
.FileCache
[F
]:
922 FullPathDependList
.append(CacheFile
)
923 if CacheFile
not in DependencySet
:
924 FileStack
.append(CacheFile
)
925 DependencySet
.update(FullPathDependList
)
928 CurrentFileDependencyList
= []
930 CurrentFileDependencyList
= DepDb
[F
]
933 Fd
= open(F
.Path
, 'r')
934 except BaseException
, X
:
935 EdkLogger
.error("build", FILE_OPEN_FAILURE
, ExtraData
=F
.Path
+ "\n\t" + str(X
))
937 FileContent
= Fd
.read()
939 if len(FileContent
) == 0:
942 if FileContent
[0] == 0xff or FileContent
[0] == 0xfe:
943 FileContent
= unicode(FileContent
, "utf-16")
944 IncludedFileList
= gIncludePattern
.findall(FileContent
)
946 for Inc
in IncludedFileList
:
948 # if there's macro used to reference header file, expand it
949 HeaderList
= gMacroPattern
.findall(Inc
)
950 if len(HeaderList
) == 1 and len(HeaderList
[0]) == 2:
951 HeaderType
= HeaderList
[0][0]
952 HeaderKey
= HeaderList
[0][1]
953 if HeaderType
in gIncludeMacroConversion
:
954 Inc
= gIncludeMacroConversion
[HeaderType
] % {"HeaderKey" : HeaderKey
}
956 # not known macro used in #include, always build the file by
957 # returning a empty dependency
958 self
.FileCache
[File
] = []
960 Inc
= os
.path
.normpath(Inc
)
961 CurrentFileDependencyList
.append(Inc
)
962 DepDb
[F
] = CurrentFileDependencyList
964 CurrentFilePath
= F
.Dir
965 PathList
= [CurrentFilePath
] + SearchPathList
966 for Inc
in CurrentFileDependencyList
:
967 for SearchPath
in PathList
:
968 FilePath
= os
.path
.join(SearchPath
, Inc
)
969 if FilePath
in gIsFileMap
:
970 if not gIsFileMap
[FilePath
]:
972 # If isfile is called too many times, the performance is slow down.
973 elif not os
.path
.isfile(FilePath
):
974 gIsFileMap
[FilePath
] = False
977 gIsFileMap
[FilePath
] = True
978 FilePath
= PathClass(FilePath
)
979 FullPathDependList
.append(FilePath
)
980 if FilePath
not in DependencySet
:
981 FileStack
.append(FilePath
)
984 EdkLogger
.debug(EdkLogger
.DEBUG_9
, "%s included by %s was not found "\
985 "in any given path:\n\t%s" % (Inc
, F
, "\n\t".join(SearchPathList
)))
987 self
.FileCache
[F
] = FullPathDependList
988 DependencySet
.update(FullPathDependList
)
990 DependencySet
.update(ForceList
)
991 if File
in DependencySet
:
992 DependencySet
.remove(File
)
993 DependencyList
= list(DependencySet
) # remove duplicate ones
995 return DependencyList
997 _TemplateDict
= property(_CreateTemplateDict
)
999 ## CustomMakefile class
1001 # This class encapsules makefie and its generation for module. It uses template to generate
1002 # the content of makefile. The content of makefile will be got from ModuleAutoGen object.
1004 class CustomMakefile(BuildFile
):
1005 ## template used to generate the makefile for module with custom makefile
1006 _TEMPLATE_
= TemplateString('''\
1010 # Platform Macro Definition
1012 PLATFORM_NAME = ${platform_name}
1013 PLATFORM_GUID = ${platform_guid}
1014 PLATFORM_VERSION = ${platform_version}
1015 PLATFORM_RELATIVE_DIR = ${platform_relative_directory}
1016 PLATFORM_DIR = ${platform_dir}
1017 PLATFORM_OUTPUT_DIR = ${platform_output_directory}
1020 # Module Macro Definition
1022 MODULE_NAME = ${module_name}
1023 MODULE_GUID = ${module_guid}
1024 MODULE_NAME_GUID = ${module_name_guid}
1025 MODULE_VERSION = ${module_version}
1026 MODULE_TYPE = ${module_type}
1027 MODULE_FILE = ${module_file}
1028 MODULE_FILE_BASE_NAME = ${module_file_base_name}
1029 BASE_NAME = $(MODULE_NAME)
1030 MODULE_RELATIVE_DIR = ${module_relative_directory}
1031 MODULE_DIR = ${module_dir}
1034 # Build Configuration Macro Definition
1036 ARCH = ${architecture}
1037 TOOLCHAIN = ${toolchain_tag}
1038 TOOLCHAIN_TAG = ${toolchain_tag}
1039 TARGET = ${build_target}
1042 # Build Directory Macro Definition
1044 # PLATFORM_BUILD_DIR = ${platform_build_directory}
1045 BUILD_DIR = ${platform_build_directory}
1046 BIN_DIR = $(BUILD_DIR)${separator}${architecture}
1047 LIB_DIR = $(BIN_DIR)
1048 MODULE_BUILD_DIR = ${module_build_directory}
1049 OUTPUT_DIR = ${module_output_directory}
1050 DEBUG_DIR = ${module_debug_directory}
1051 DEST_DIR_OUTPUT = $(OUTPUT_DIR)
1052 DEST_DIR_DEBUG = $(DEBUG_DIR)
1055 # Tools definitions specific to this module
1057 ${BEGIN}${module_tool_definitions}
1059 MAKE_FILE = ${makefile_path}
1062 # Shell Command Macro
1064 ${BEGIN}${shell_command_code} = ${shell_command}
1067 ${custom_makefile_content}
1070 # Target used when called from platform makefile, which will bypass the build of dependent libraries
1083 # Build Target used in multi-thread build mode, which no init target is needed
1089 # Initialization target: print build information and create necessary directories
1092 \t-@echo Building ... $(MODULE_DIR)${separator}$(MODULE_FILE) [$(ARCH)]
1093 ${BEGIN}\t-@${create_directory_command}\n${END}\
1097 ## Constructor of CustomMakefile
1099 # @param ModuleAutoGen Object of ModuleAutoGen class
1101 def __init__(self
, ModuleAutoGen
):
1102 BuildFile
.__init
__(self
, ModuleAutoGen
)
1103 self
.PlatformInfo
= self
._AutoGenObject
.PlatformInfo
1104 self
.IntermediateDirectoryList
= ["$(DEBUG_DIR)", "$(OUTPUT_DIR)"]
1106 # Compose a dict object containing information used to do replacement in template
1107 def _CreateTemplateDict(self
):
1108 Separator
= self
._SEP
_[self
._FileType
]
1109 if self
._FileType
not in self
._AutoGenObject
.CustomMakefile
:
1110 EdkLogger
.error('build', OPTION_NOT_SUPPORTED
, "No custom makefile for %s" % self
._FileType
,
1111 ExtraData
="[%s]" % str(self
._AutoGenObject
))
1112 MakefilePath
= mws
.join(
1113 self
._AutoGenObject
.WorkspaceDir
,
1114 self
._AutoGenObject
.CustomMakefile
[self
._FileType
]
1117 CustomMakefile
= open(MakefilePath
, 'r').read()
1119 EdkLogger
.error('build', FILE_OPEN_FAILURE
, File
=str(self
._AutoGenObject
),
1120 ExtraData
=self
._AutoGenObject
.CustomMakefile
[self
._FileType
])
1124 for Tool
in self
._AutoGenObject
.BuildOption
:
1125 # Don't generate MAKE_FLAGS in makefile. It's put in environment variable.
1128 for Attr
in self
._AutoGenObject
.BuildOption
[Tool
]:
1129 if Attr
== "FAMILY":
1131 elif Attr
== "PATH":
1132 ToolsDef
.append("%s = %s" % (Tool
, self
._AutoGenObject
.BuildOption
[Tool
][Attr
]))
1134 ToolsDef
.append("%s_%s = %s" % (Tool
, Attr
, self
._AutoGenObject
.BuildOption
[Tool
][Attr
]))
1137 MakefileName
= self
._FILE
_NAME
_[self
._FileType
]
1138 MakefileTemplateDict
= {
1139 "makefile_header" : self
._FILE
_HEADER
_[self
._FileType
],
1140 "makefile_path" : os
.path
.join("$(MODULE_BUILD_DIR)", MakefileName
),
1141 "platform_name" : self
.PlatformInfo
.Name
,
1142 "platform_guid" : self
.PlatformInfo
.Guid
,
1143 "platform_version" : self
.PlatformInfo
.Version
,
1144 "platform_relative_directory": self
.PlatformInfo
.SourceDir
,
1145 "platform_output_directory" : self
.PlatformInfo
.OutputDir
,
1146 "platform_dir" : self
._AutoGenObject
.Macros
["PLATFORM_DIR"],
1148 "module_name" : self
._AutoGenObject
.Name
,
1149 "module_guid" : self
._AutoGenObject
.Guid
,
1150 "module_name_guid" : self
._AutoGenObject
._GetUniqueBaseName
(),
1151 "module_version" : self
._AutoGenObject
.Version
,
1152 "module_type" : self
._AutoGenObject
.ModuleType
,
1153 "module_file" : self
._AutoGenObject
.MetaFile
,
1154 "module_file_base_name" : self
._AutoGenObject
.MetaFile
.BaseName
,
1155 "module_relative_directory" : self
._AutoGenObject
.SourceDir
,
1156 "module_dir" : mws
.join (self
._AutoGenObject
.WorkspaceDir
, self
._AutoGenObject
.SourceDir
),
1158 "architecture" : self
._AutoGenObject
.Arch
,
1159 "toolchain_tag" : self
._AutoGenObject
.ToolChain
,
1160 "build_target" : self
._AutoGenObject
.BuildTarget
,
1162 "platform_build_directory" : self
.PlatformInfo
.BuildDir
,
1163 "module_build_directory" : self
._AutoGenObject
.BuildDir
,
1164 "module_output_directory" : self
._AutoGenObject
.OutputDir
,
1165 "module_debug_directory" : self
._AutoGenObject
.DebugDir
,
1167 "separator" : Separator
,
1168 "module_tool_definitions" : ToolsDef
,
1170 "shell_command_code" : self
._SHELL
_CMD
_[self
._FileType
].keys(),
1171 "shell_command" : self
._SHELL
_CMD
_[self
._FileType
].values(),
1173 "create_directory_command" : self
.GetCreateDirectoryCommand(self
.IntermediateDirectoryList
),
1174 "custom_makefile_content" : CustomMakefile
1177 return MakefileTemplateDict
1179 _TemplateDict
= property(_CreateTemplateDict
)
1181 ## PlatformMakefile class
1183 # This class encapsules makefie and its generation for platform. It uses
1184 # template to generate the content of makefile. The content of makefile will be
1185 # got from PlatformAutoGen object.
1187 class PlatformMakefile(BuildFile
):
1188 ## template used to generate the makefile for platform
1189 _TEMPLATE_
= TemplateString('''\
1193 # Platform Macro Definition
1195 PLATFORM_NAME = ${platform_name}
1196 PLATFORM_GUID = ${platform_guid}
1197 PLATFORM_VERSION = ${platform_version}
1198 PLATFORM_FILE = ${platform_file}
1199 PLATFORM_DIR = ${platform_dir}
1200 PLATFORM_OUTPUT_DIR = ${platform_output_directory}
1203 # Build Configuration Macro Definition
1205 TOOLCHAIN = ${toolchain_tag}
1206 TOOLCHAIN_TAG = ${toolchain_tag}
1207 TARGET = ${build_target}
1210 # Build Directory Macro Definition
1212 BUILD_DIR = ${platform_build_directory}
1213 FV_DIR = ${platform_build_directory}${separator}FV
1216 # Shell Command Macro
1218 ${BEGIN}${shell_command_code} = ${shell_command}
1222 MAKE_FILE = ${makefile_path}
1227 all: init build_libraries build_modules
1230 # Initialization target: print build information and create necessary directories
1233 \t-@echo Building ... $(PLATFORM_FILE) [${build_architecture_list}]
1234 \t${BEGIN}-@${create_directory_command}
1237 # library build target
1239 libraries: init build_libraries
1242 # module build target
1244 modules: init build_libraries build_modules
1247 # Build all libraries:
1250 ${BEGIN}\t@"$(MAKE)" $(MAKE_FLAGS) -f ${library_makefile_list} pbuild
1251 ${END}\t@cd $(BUILD_DIR)
1254 # Build all modules:
1257 ${BEGIN}\t@"$(MAKE)" $(MAKE_FLAGS) -f ${module_makefile_list} pbuild
1258 ${END}\t@cd $(BUILD_DIR)
1261 # Clean intermediate files
1264 \t${BEGIN}-@${library_build_command} clean
1265 \t${END}${BEGIN}-@${module_build_command} clean
1266 \t${END}@cd $(BUILD_DIR)
1269 # Clean all generated files except to makefile
1272 ${BEGIN}\t${cleanall_command}
1276 # Clean all library files
1279 \t${BEGIN}-@${library_build_command} cleanall
1280 \t${END}@cd $(BUILD_DIR)\n
1283 ## Constructor of PlatformMakefile
1285 # @param ModuleAutoGen Object of PlatformAutoGen class
1287 def __init__(self
, PlatformAutoGen
):
1288 BuildFile
.__init
__(self
, PlatformAutoGen
)
1289 self
.ModuleBuildCommandList
= []
1290 self
.ModuleMakefileList
= []
1291 self
.IntermediateDirectoryList
= []
1292 self
.ModuleBuildDirectoryList
= []
1293 self
.LibraryBuildDirectoryList
= []
1294 self
.LibraryMakeCommandList
= []
1296 # Compose a dict object containing information used to do replacement in template
1297 def _CreateTemplateDict(self
):
1298 Separator
= self
._SEP
_[self
._FileType
]
1300 PlatformInfo
= self
._AutoGenObject
1301 if "MAKE" not in PlatformInfo
.ToolDefinition
or "PATH" not in PlatformInfo
.ToolDefinition
["MAKE"]:
1302 EdkLogger
.error("build", OPTION_MISSING
, "No MAKE command defined. Please check your tools_def.txt!",
1303 ExtraData
="[%s]" % str(self
._AutoGenObject
))
1305 self
.IntermediateDirectoryList
= ["$(BUILD_DIR)"]
1306 self
.ModuleBuildDirectoryList
= self
.GetModuleBuildDirectoryList()
1307 self
.LibraryBuildDirectoryList
= self
.GetLibraryBuildDirectoryList()
1309 MakefileName
= self
._FILE
_NAME
_[self
._FileType
]
1310 LibraryMakefileList
= []
1311 LibraryMakeCommandList
= []
1312 for D
in self
.LibraryBuildDirectoryList
:
1313 D
= self
.PlaceMacro(D
, {"BUILD_DIR":PlatformInfo
.BuildDir
})
1314 Makefile
= os
.path
.join(D
, MakefileName
)
1315 Command
= self
._MAKE
_TEMPLATE
_[self
._FileType
] % {"file":Makefile
}
1316 LibraryMakefileList
.append(Makefile
)
1317 LibraryMakeCommandList
.append(Command
)
1318 self
.LibraryMakeCommandList
= LibraryMakeCommandList
1320 ModuleMakefileList
= []
1321 ModuleMakeCommandList
= []
1322 for D
in self
.ModuleBuildDirectoryList
:
1323 D
= self
.PlaceMacro(D
, {"BUILD_DIR":PlatformInfo
.BuildDir
})
1324 Makefile
= os
.path
.join(D
, MakefileName
)
1325 Command
= self
._MAKE
_TEMPLATE
_[self
._FileType
] % {"file":Makefile
}
1326 ModuleMakefileList
.append(Makefile
)
1327 ModuleMakeCommandList
.append(Command
)
1329 MakefileTemplateDict
= {
1330 "makefile_header" : self
._FILE
_HEADER
_[self
._FileType
],
1331 "makefile_path" : os
.path
.join("$(BUILD_DIR)", MakefileName
),
1332 "make_path" : PlatformInfo
.ToolDefinition
["MAKE"]["PATH"],
1333 "makefile_name" : MakefileName
,
1334 "platform_name" : PlatformInfo
.Name
,
1335 "platform_guid" : PlatformInfo
.Guid
,
1336 "platform_version" : PlatformInfo
.Version
,
1337 "platform_file" : self
._AutoGenObject
.MetaFile
,
1338 "platform_relative_directory": PlatformInfo
.SourceDir
,
1339 "platform_output_directory" : PlatformInfo
.OutputDir
,
1340 "platform_build_directory" : PlatformInfo
.BuildDir
,
1341 "platform_dir" : self
._AutoGenObject
.Macros
["PLATFORM_DIR"],
1343 "toolchain_tag" : PlatformInfo
.ToolChain
,
1344 "build_target" : PlatformInfo
.BuildTarget
,
1345 "shell_command_code" : self
._SHELL
_CMD
_[self
._FileType
].keys(),
1346 "shell_command" : self
._SHELL
_CMD
_[self
._FileType
].values(),
1347 "build_architecture_list" : self
._AutoGenObject
.Arch
,
1348 "architecture" : self
._AutoGenObject
.Arch
,
1349 "separator" : Separator
,
1350 "create_directory_command" : self
.GetCreateDirectoryCommand(self
.IntermediateDirectoryList
),
1351 "cleanall_command" : self
.GetRemoveDirectoryCommand(self
.IntermediateDirectoryList
),
1352 "library_makefile_list" : LibraryMakefileList
,
1353 "module_makefile_list" : ModuleMakefileList
,
1354 "library_build_command" : LibraryMakeCommandList
,
1355 "module_build_command" : ModuleMakeCommandList
,
1358 return MakefileTemplateDict
1360 ## Get the root directory list for intermediate files of all modules build
1362 # @retval list The list of directory
1364 def GetModuleBuildDirectoryList(self
):
1366 for ModuleAutoGen
in self
._AutoGenObject
.ModuleAutoGenList
:
1367 if not ModuleAutoGen
.IsBinaryModule
:
1368 DirList
.append(os
.path
.join(self
._AutoGenObject
.BuildDir
, ModuleAutoGen
.BuildDir
))
1371 ## Get the root directory list for intermediate files of all libraries build
1373 # @retval list The list of directory
1375 def GetLibraryBuildDirectoryList(self
):
1377 for LibraryAutoGen
in self
._AutoGenObject
.LibraryAutoGenList
:
1378 if not LibraryAutoGen
.IsBinaryModule
:
1379 DirList
.append(os
.path
.join(self
._AutoGenObject
.BuildDir
, LibraryAutoGen
.BuildDir
))
1382 _TemplateDict
= property(_CreateTemplateDict
)
1384 ## TopLevelMakefile class
1386 # This class encapsules makefie and its generation for entrance makefile. It
1387 # uses template to generate the content of makefile. The content of makefile
1388 # will be got from WorkspaceAutoGen object.
1390 class TopLevelMakefile(BuildFile
):
1391 ## template used to generate toplevel makefile
1392 _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}''')
1394 ## Constructor of TopLevelMakefile
1396 # @param Workspace Object of WorkspaceAutoGen class
1398 def __init__(self
, Workspace
):
1399 BuildFile
.__init
__(self
, Workspace
)
1400 self
.IntermediateDirectoryList
= []
1402 # Compose a dict object containing information used to do replacement in template
1403 def _CreateTemplateDict(self
):
1404 Separator
= self
._SEP
_[self
._FileType
]
1406 # any platform autogen object is ok because we just need common information
1407 PlatformInfo
= self
._AutoGenObject
1409 if "MAKE" not in PlatformInfo
.ToolDefinition
or "PATH" not in PlatformInfo
.ToolDefinition
["MAKE"]:
1410 EdkLogger
.error("build", OPTION_MISSING
, "No MAKE command defined. Please check your tools_def.txt!",
1411 ExtraData
="[%s]" % str(self
._AutoGenObject
))
1413 for Arch
in PlatformInfo
.ArchList
:
1414 self
.IntermediateDirectoryList
.append(Separator
.join(["$(BUILD_DIR)", Arch
]))
1415 self
.IntermediateDirectoryList
.append("$(FV_DIR)")
1417 # TRICK: for not generating GenFds call in makefile if no FDF file
1419 if PlatformInfo
.FdfFile
!= None and PlatformInfo
.FdfFile
!= "":
1420 FdfFileList
= [PlatformInfo
.FdfFile
]
1421 # macros passed to GenFds
1422 MacroList
.append('"%s=%s"' % ("EFI_SOURCE", GlobalData
.gEfiSource
.replace('\\', '\\\\')))
1423 MacroList
.append('"%s=%s"' % ("EDK_SOURCE", GlobalData
.gEdkSource
.replace('\\', '\\\\')))
1425 MacroDict
.update(GlobalData
.gGlobalDefines
)
1426 MacroDict
.update(GlobalData
.gCommandLineDefines
)
1427 MacroDict
.pop("EFI_SOURCE", "dummy")
1428 MacroDict
.pop("EDK_SOURCE", "dummy")
1429 for MacroName
in MacroDict
:
1430 if MacroDict
[MacroName
] != "":
1431 MacroList
.append('"%s=%s"' % (MacroName
, MacroDict
[MacroName
].replace('\\', '\\\\')))
1433 MacroList
.append('"%s"' % MacroName
)
1437 # pass extra common options to external program called in makefile, currently GenFds.exe
1439 LogLevel
= EdkLogger
.GetLevel()
1440 if LogLevel
== EdkLogger
.VERBOSE
:
1441 ExtraOption
+= " -v"
1442 elif LogLevel
<= EdkLogger
.DEBUG_9
:
1443 ExtraOption
+= " -d %d" % (LogLevel
- 1)
1444 elif LogLevel
== EdkLogger
.QUIET
:
1445 ExtraOption
+= " -q"
1447 if GlobalData
.gCaseInsensitive
:
1448 ExtraOption
+= " -c"
1450 if GlobalData
.gIgnoreSource
:
1451 ExtraOption
+= " --ignore-sources"
1453 if GlobalData
.BuildOptionPcd
:
1454 for index
, option
in enumerate(GlobalData
.gCommand
):
1455 if "--pcd" == option
and GlobalData
.gCommand
[index
+1]:
1456 pcdName
, pcdValue
= GlobalData
.gCommand
[index
+1].split('=')
1457 if pcdValue
.startswith('H'):
1458 pcdValue
= 'H' + '"' + pcdValue
[1:] + '"'
1459 ExtraOption
+= " --pcd " + pcdName
+ '=' + pcdValue
1460 elif pcdValue
.startswith('L'):
1461 pcdValue
= 'L' + '"' + pcdValue
[1:] + '"'
1462 ExtraOption
+= " --pcd " + pcdName
+ '=' + pcdValue
1464 ExtraOption
+= " --pcd " + GlobalData
.gCommand
[index
+1]
1466 MakefileName
= self
._FILE
_NAME
_[self
._FileType
]
1467 SubBuildCommandList
= []
1468 for A
in PlatformInfo
.ArchList
:
1469 Command
= self
._MAKE
_TEMPLATE
_[self
._FileType
] % {"file":os
.path
.join("$(BUILD_DIR)", A
, MakefileName
)}
1470 SubBuildCommandList
.append(Command
)
1472 MakefileTemplateDict
= {
1473 "makefile_header" : self
._FILE
_HEADER
_[self
._FileType
],
1474 "makefile_path" : os
.path
.join("$(BUILD_DIR)", MakefileName
),
1475 "make_path" : PlatformInfo
.ToolDefinition
["MAKE"]["PATH"],
1476 "platform_name" : PlatformInfo
.Name
,
1477 "platform_guid" : PlatformInfo
.Guid
,
1478 "platform_version" : PlatformInfo
.Version
,
1479 "platform_build_directory" : PlatformInfo
.BuildDir
,
1480 "conf_directory" : GlobalData
.gConfDirectory
,
1482 "toolchain_tag" : PlatformInfo
.ToolChain
,
1483 "build_target" : PlatformInfo
.BuildTarget
,
1484 "shell_command_code" : self
._SHELL
_CMD
_[self
._FileType
].keys(),
1485 "shell_command" : self
._SHELL
_CMD
_[self
._FileType
].values(),
1486 'arch' : list(PlatformInfo
.ArchList
),
1487 "build_architecture_list" : ','.join(PlatformInfo
.ArchList
),
1488 "separator" : Separator
,
1489 "create_directory_command" : self
.GetCreateDirectoryCommand(self
.IntermediateDirectoryList
),
1490 "cleanall_command" : self
.GetRemoveDirectoryCommand(self
.IntermediateDirectoryList
),
1491 "sub_build_command" : SubBuildCommandList
,
1492 "fdf_file" : FdfFileList
,
1493 "active_platform" : str(PlatformInfo
),
1494 "fd" : PlatformInfo
.FdTargetList
,
1495 "fv" : PlatformInfo
.FvTargetList
,
1496 "cap" : PlatformInfo
.CapTargetList
,
1497 "extra_options" : ExtraOption
,
1498 "macro" : MacroList
,
1501 return MakefileTemplateDict
1503 ## Get the root directory list for intermediate files of all modules build
1505 # @retval list The list of directory
1507 def GetModuleBuildDirectoryList(self
):
1509 for ModuleAutoGen
in self
._AutoGenObject
.ModuleAutoGenList
:
1510 if not ModuleAutoGen
.IsBinaryModule
:
1511 DirList
.append(os
.path
.join(self
._AutoGenObject
.BuildDir
, ModuleAutoGen
.BuildDir
))
1514 ## Get the root directory list for intermediate files of all libraries build
1516 # @retval list The list of directory
1518 def GetLibraryBuildDirectoryList(self
):
1520 for LibraryAutoGen
in self
._AutoGenObject
.LibraryAutoGenList
:
1521 if not LibraryAutoGen
.IsBinaryModule
:
1522 DirList
.append(os
.path
.join(self
._AutoGenObject
.BuildDir
, LibraryAutoGen
.BuildDir
))
1525 _TemplateDict
= property(_CreateTemplateDict
)
1527 # This acts like the main() function for the script, unless it is 'import'ed into another script.
1528 if __name__
== '__main__':