]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/AutoGen/GenMake.py
BaseTools: Add a checking for Sources section in INF file
[mirror_edk2.git] / BaseTools / Source / Python / AutoGen / GenMake.py
CommitLineData
f51461c8
LG
1## @file\r
2# Create makefile for MS nmake and GNU make\r
3#\r
70d0a754 4# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>\r
2e351cbe 5# SPDX-License-Identifier: BSD-2-Clause-Patent\r
f51461c8
LG
6#\r
7\r
8## Import Modules\r
9#\r
1ccc4d89 10from __future__ import absolute_import\r
1be2ed90 11import Common.LongFilePathOs as os\r
f51461c8
LG
12import sys\r
13import string\r
14import re\r
15import os.path as path\r
1be2ed90 16from Common.LongFilePathSupport import OpenLongFilePath as open\r
05cc51ad 17from Common.MultipleWorkspace import MultipleWorkspace as mws\r
f51461c8
LG
18from Common.BuildToolError import *\r
19from Common.Misc import *\r
5a57246e 20from Common.StringUtils import *\r
0ff3b52e 21from .BuildEngine import *\r
f51461c8 22import Common.GlobalData as GlobalData\r
9006a2c6 23from collections import OrderedDict\r
94c04559 24from Common.DataType import TAB_COMPILER_MSFT\r
f51461c8
LG
25\r
26## Regular expression for finding header file inclusions\r
5061efe7 27gIncludePattern = re.compile(r"^[ \t]*[#%]?[ \t]*include(?:[ \t]*(?:\\(?:\r\n|\r|\n))*[ \t]*)*(?:\(?[\"<]?[ \t]*)([-\w.\\/() \t]+)(?:[ \t]*[\">]?\)?)", re.MULTILINE | re.UNICODE | re.IGNORECASE)\r
f51461c8
LG
28\r
29## Regular expression for matching macro used in header file inclusion\r
30gMacroPattern = re.compile("([_A-Z][_A-Z0-9]*)[ \t]*\((.+)\)", re.UNICODE)\r
31\r
32gIsFileMap = {}\r
33\r
34## pattern for include style in Edk.x code\r
35gProtocolDefinition = "Protocol/%(HeaderKey)s/%(HeaderKey)s.h"\r
36gGuidDefinition = "Guid/%(HeaderKey)s/%(HeaderKey)s.h"\r
37gArchProtocolDefinition = "ArchProtocol/%(HeaderKey)s/%(HeaderKey)s.h"\r
38gPpiDefinition = "Ppi/%(HeaderKey)s/%(HeaderKey)s.h"\r
39gIncludeMacroConversion = {\r
40 "EFI_PROTOCOL_DEFINITION" : gProtocolDefinition,\r
41 "EFI_GUID_DEFINITION" : gGuidDefinition,\r
42 "EFI_ARCH_PROTOCOL_DEFINITION" : gArchProtocolDefinition,\r
43 "EFI_PROTOCOL_PRODUCER" : gProtocolDefinition,\r
44 "EFI_PROTOCOL_CONSUMER" : gProtocolDefinition,\r
45 "EFI_PROTOCOL_DEPENDENCY" : gProtocolDefinition,\r
46 "EFI_ARCH_PROTOCOL_PRODUCER" : gArchProtocolDefinition,\r
47 "EFI_ARCH_PROTOCOL_CONSUMER" : gArchProtocolDefinition,\r
48 "EFI_ARCH_PROTOCOL_DEPENDENCY" : gArchProtocolDefinition,\r
49 "EFI_PPI_DEFINITION" : gPpiDefinition,\r
50 "EFI_PPI_PRODUCER" : gPpiDefinition,\r
51 "EFI_PPI_CONSUMER" : gPpiDefinition,\r
52 "EFI_PPI_DEPENDENCY" : gPpiDefinition,\r
53}\r
54\r
55## default makefile type\r
56gMakeType = ""\r
57if sys.platform == "win32":\r
58 gMakeType = "nmake"\r
59else:\r
60 gMakeType = "gmake"\r
61\r
62\r
63## BuildFile class\r
64#\r
65# This base class encapsules build file and its generation. It uses template to generate\r
66# the content of build file. The content of build file will be got from AutoGen objects.\r
67#\r
68class BuildFile(object):\r
69 ## template used to generate the build file (i.e. makefile if using make)\r
70 _TEMPLATE_ = TemplateString('')\r
71\r
72 _DEFAULT_FILE_NAME_ = "Makefile"\r
73\r
74 ## default file name for each type of build file\r
75 _FILE_NAME_ = {\r
76 "nmake" : "Makefile",\r
77 "gmake" : "GNUmakefile"\r
78 }\r
79\r
80 ## Fixed header string for makefile\r
81 _MAKEFILE_HEADER = '''#\r
82# DO NOT EDIT\r
83# This file is auto-generated by build utility\r
84#\r
85# Module Name:\r
86#\r
87# %s\r
88#\r
89# Abstract:\r
90#\r
91# Auto-generated makefile for building modules, libraries or platform\r
92#\r
93 '''\r
94\r
95 ## Header string for each type of build file\r
96 _FILE_HEADER_ = {\r
97 "nmake" : _MAKEFILE_HEADER % _FILE_NAME_["nmake"],\r
98 "gmake" : _MAKEFILE_HEADER % _FILE_NAME_["gmake"]\r
99 }\r
100\r
101 ## shell commands which can be used in build file in the form of macro\r
102 # $(CP) copy file command\r
103 # $(MV) move file command\r
104 # $(RM) remove file command\r
105 # $(MD) create dir command\r
106 # $(RD) remove dir command\r
107 #\r
108 _SHELL_CMD_ = {\r
109 "nmake" : {\r
110 "CP" : "copy /y",\r
111 "MV" : "move /y",\r
112 "RM" : "del /f /q",\r
113 "MD" : "mkdir",\r
114 "RD" : "rmdir /s /q",\r
115 },\r
116\r
117 "gmake" : {\r
118 "CP" : "cp -f",\r
119 "MV" : "mv -f",\r
120 "RM" : "rm -f",\r
121 "MD" : "mkdir -p",\r
122 "RD" : "rm -r -f",\r
123 }\r
124 }\r
125\r
126 ## directory separator\r
127 _SEP_ = {\r
128 "nmake" : "\\",\r
129 "gmake" : "/"\r
130 }\r
131\r
132 ## directory creation template\r
133 _MD_TEMPLATE_ = {\r
134 "nmake" : 'if not exist %(dir)s $(MD) %(dir)s',\r
135 "gmake" : "$(MD) %(dir)s"\r
136 }\r
137\r
138 ## directory removal template\r
139 _RD_TEMPLATE_ = {\r
140 "nmake" : 'if exist %(dir)s $(RD) %(dir)s',\r
141 "gmake" : "$(RD) %(dir)s"\r
142 }\r
37de70b7
YZ
143 ## cp if exist\r
144 _CP_TEMPLATE_ = {\r
145 "nmake" : 'if exist %(Src)s $(CP) %(Src)s %(Dst)s',\r
146 "gmake" : "test -f %(Src)s && $(CP) %(Src)s %(Dst)s"\r
147 }\r
f51461c8
LG
148\r
149 _CD_TEMPLATE_ = {\r
150 "nmake" : 'if exist %(dir)s cd %(dir)s',\r
151 "gmake" : "test -e %(dir)s && cd %(dir)s"\r
152 }\r
153\r
154 _MAKE_TEMPLATE_ = {\r
155 "nmake" : 'if exist %(file)s "$(MAKE)" $(MAKE_FLAGS) -f %(file)s',\r
156 "gmake" : 'test -e %(file)s && "$(MAKE)" $(MAKE_FLAGS) -f %(file)s'\r
157 }\r
158\r
159 _INCLUDE_CMD_ = {\r
160 "nmake" : '!INCLUDE',\r
161 "gmake" : "include"\r
162 }\r
163\r
073a76e6 164 _INC_FLAG_ = {TAB_COMPILER_MSFT : "/I", "GCC" : "-I", "INTEL" : "-I", "RVCT" : "-I", "NASM" : "-I"}\r
f51461c8
LG
165\r
166 ## Constructor of BuildFile\r
167 #\r
168 # @param AutoGenObject Object of AutoGen class\r
169 #\r
170 def __init__(self, AutoGenObject):\r
171 self._AutoGenObject = AutoGenObject\r
172 self._FileType = gMakeType\r
173\r
174 ## Create build file\r
175 #\r
176 # @param FileType Type of build file. Only nmake and gmake are supported now.\r
177 #\r
178 # @retval TRUE The build file is created or re-created successfully\r
179 # @retval FALSE The build file exists and is the same as the one to be generated\r
180 #\r
181 def Generate(self, FileType=gMakeType):\r
182 if FileType not in self._FILE_NAME_:\r
183 EdkLogger.error("build", PARAMETER_INVALID, "Invalid build type [%s]" % FileType,\r
184 ExtraData="[%s]" % str(self._AutoGenObject))\r
185 self._FileType = FileType\r
186 FileContent = self._TEMPLATE_.Replace(self._TemplateDict)\r
187 FileName = self._FILE_NAME_[FileType]\r
188 return SaveFileOnChange(os.path.join(self._AutoGenObject.MakeFileDir, FileName), FileContent, False)\r
189\r
190 ## Return a list of directory creation command string\r
191 #\r
192 # @param DirList The list of directory to be created\r
193 #\r
194 # @retval list The directory creation command list\r
195 #\r
196 def GetCreateDirectoryCommand(self, DirList):\r
197 return [self._MD_TEMPLATE_[self._FileType] % {'dir':Dir} for Dir in DirList]\r
198\r
199 ## Return a list of directory removal command string\r
200 #\r
201 # @param DirList The list of directory to be removed\r
202 #\r
203 # @retval list The directory removal command list\r
204 #\r
205 def GetRemoveDirectoryCommand(self, DirList):\r
206 return [self._RD_TEMPLATE_[self._FileType] % {'dir':Dir} for Dir in DirList]\r
207\r
208 def PlaceMacro(self, Path, MacroDefinitions={}):\r
209 if Path.startswith("$("):\r
210 return Path\r
211 else:\r
212 PathLength = len(Path)\r
213 for MacroName in MacroDefinitions:\r
214 MacroValue = MacroDefinitions[MacroName]\r
215 MacroValueLength = len(MacroValue)\r
37de70b7
YZ
216 if MacroValueLength == 0:\r
217 continue\r
f51461c8
LG
218 if MacroValueLength <= PathLength and Path.startswith(MacroValue):\r
219 Path = "$(%s)%s" % (MacroName, Path[MacroValueLength:])\r
220 break\r
221 return Path\r
222\r
223## ModuleMakefile class\r
224#\r
225# This class encapsules makefie and its generation for module. It uses template to generate\r
226# the content of makefile. The content of makefile will be got from ModuleAutoGen object.\r
227#\r
228class ModuleMakefile(BuildFile):\r
229 ## template used to generate the makefile for module\r
230 _TEMPLATE_ = TemplateString('''\\r
231${makefile_header}\r
232\r
233#\r
234# Platform Macro Definition\r
235#\r
236PLATFORM_NAME = ${platform_name}\r
237PLATFORM_GUID = ${platform_guid}\r
238PLATFORM_VERSION = ${platform_version}\r
239PLATFORM_RELATIVE_DIR = ${platform_relative_directory}\r
017fb1cd 240PLATFORM_DIR = ${platform_dir}\r
f51461c8
LG
241PLATFORM_OUTPUT_DIR = ${platform_output_directory}\r
242\r
243#\r
244# Module Macro Definition\r
245#\r
246MODULE_NAME = ${module_name}\r
247MODULE_GUID = ${module_guid}\r
867d1cd4 248MODULE_NAME_GUID = ${module_name_guid}\r
f51461c8
LG
249MODULE_VERSION = ${module_version}\r
250MODULE_TYPE = ${module_type}\r
251MODULE_FILE = ${module_file}\r
252MODULE_FILE_BASE_NAME = ${module_file_base_name}\r
253BASE_NAME = $(MODULE_NAME)\r
254MODULE_RELATIVE_DIR = ${module_relative_directory}\r
97fa0ee9 255PACKAGE_RELATIVE_DIR = ${package_relative_directory}\r
01e418d6 256MODULE_DIR = ${module_dir}\r
37de70b7 257FFS_OUTPUT_DIR = ${ffs_output_directory}\r
f51461c8
LG
258\r
259MODULE_ENTRY_POINT = ${module_entry_point}\r
260ARCH_ENTRY_POINT = ${arch_entry_point}\r
261IMAGE_ENTRY_POINT = ${image_entry_point}\r
262\r
263${BEGIN}${module_extra_defines}\r
264${END}\r
265#\r
266# Build Configuration Macro Definition\r
267#\r
268ARCH = ${architecture}\r
269TOOLCHAIN = ${toolchain_tag}\r
270TOOLCHAIN_TAG = ${toolchain_tag}\r
271TARGET = ${build_target}\r
272\r
273#\r
274# Build Directory Macro Definition\r
275#\r
276# PLATFORM_BUILD_DIR = ${platform_build_directory}\r
277BUILD_DIR = ${platform_build_directory}\r
278BIN_DIR = $(BUILD_DIR)${separator}${architecture}\r
279LIB_DIR = $(BIN_DIR)\r
280MODULE_BUILD_DIR = ${module_build_directory}\r
281OUTPUT_DIR = ${module_output_directory}\r
282DEBUG_DIR = ${module_debug_directory}\r
283DEST_DIR_OUTPUT = $(OUTPUT_DIR)\r
284DEST_DIR_DEBUG = $(DEBUG_DIR)\r
285\r
286#\r
287# Shell Command Macro\r
288#\r
289${BEGIN}${shell_command_code} = ${shell_command}\r
290${END}\r
291\r
292#\r
293# Tools definitions specific to this module\r
294#\r
295${BEGIN}${module_tool_definitions}\r
296${END}\r
297MAKE_FILE = ${makefile_path}\r
298\r
299#\r
300# Build Macro\r
301#\r
302${BEGIN}${file_macro}\r
303${END}\r
304\r
305COMMON_DEPS = ${BEGIN}${common_dependency_file} \\\r
306 ${END}\r
307\r
308#\r
309# Overridable Target Macro Definitions\r
310#\r
311FORCE_REBUILD = force_build\r
312INIT_TARGET = init\r
313PCH_TARGET =\r
314BC_TARGET = ${BEGIN}${backward_compatible_target} ${END}\r
315CODA_TARGET = ${BEGIN}${remaining_build_target} \\\r
316 ${END}\r
317\r
318#\r
319# Default target, which will build dependent libraries in addition to source files\r
320#\r
321\r
322all: mbuild\r
323\r
324\r
325#\r
326# Target used when called from platform makefile, which will bypass the build of dependent libraries\r
327#\r
328\r
329pbuild: $(INIT_TARGET) $(BC_TARGET) $(PCH_TARGET) $(CODA_TARGET)\r
330\r
331#\r
332# ModuleTarget\r
333#\r
334\r
335mbuild: $(INIT_TARGET) $(BC_TARGET) gen_libs $(PCH_TARGET) $(CODA_TARGET)\r
336\r
337#\r
338# Build Target used in multi-thread build mode, which will bypass the init and gen_libs targets\r
339#\r
340\r
341tbuild: $(BC_TARGET) $(PCH_TARGET) $(CODA_TARGET)\r
342\r
343#\r
344# Phony target which is used to force executing commands for a target\r
345#\r
346force_build:\r
347\t-@\r
348\r
349#\r
350# Target to update the FD\r
351#\r
352\r
353fds: mbuild gen_fds\r
354\r
355#\r
356# Initialization target: print build information and create necessary directories\r
357#\r
358init: info dirs\r
359\r
360info:\r
361\t-@echo Building ... $(MODULE_DIR)${separator}$(MODULE_FILE) [$(ARCH)]\r
362\r
363dirs:\r
364${BEGIN}\t-@${create_directory_command}\n${END}\r
365\r
366strdefs:\r
367\t-@$(CP) $(DEBUG_DIR)${separator}AutoGen.h $(DEBUG_DIR)${separator}$(MODULE_NAME)StrDefs.h\r
368\r
369#\r
370# GenLibsTarget\r
371#\r
372gen_libs:\r
373\t${BEGIN}@"$(MAKE)" $(MAKE_FLAGS) -f ${dependent_library_build_directory}${separator}${makefile_name}\r
374\t${END}@cd $(MODULE_BUILD_DIR)\r
375\r
376#\r
377# Build Flash Device Image\r
378#\r
379gen_fds:\r
380\t@"$(MAKE)" $(MAKE_FLAGS) -f $(BUILD_DIR)${separator}${makefile_name} fds\r
381\t@cd $(MODULE_BUILD_DIR)\r
382\r
383#\r
384# Individual Object Build Targets\r
385#\r
386${BEGIN}${file_build_target}\r
387${END}\r
388\r
389#\r
390# clean all intermediate files\r
391#\r
392clean:\r
393\t${BEGIN}${clean_command}\r
8ac3309f 394\t${END}\t$(RM) AutoGenTimeStamp\r
f51461c8
LG
395\r
396#\r
397# clean all generated files\r
398#\r
399cleanall:\r
400${BEGIN}\t${cleanall_command}\r
401${END}\t$(RM) *.pdb *.idb > NUL 2>&1\r
402\t$(RM) $(BIN_DIR)${separator}$(MODULE_NAME).efi\r
8ac3309f 403\t$(RM) AutoGenTimeStamp\r
f51461c8
LG
404\r
405#\r
406# clean all dependent libraries built\r
407#\r
408cleanlib:\r
409\t${BEGIN}-@${library_build_command} cleanall\r
410\t${END}@cd $(MODULE_BUILD_DIR)\n\n''')\r
411\r
412 _FILE_MACRO_TEMPLATE = TemplateString("${macro_name} = ${BEGIN} \\\n ${source_file}${END}\n")\r
413 _BUILD_TARGET_TEMPLATE = TemplateString("${BEGIN}${target} : ${deps}\n${END}\t${cmd}\n")\r
414\r
415 ## Constructor of ModuleMakefile\r
416 #\r
417 # @param ModuleAutoGen Object of ModuleAutoGen class\r
418 #\r
419 def __init__(self, ModuleAutoGen):\r
420 BuildFile.__init__(self, ModuleAutoGen)\r
421 self.PlatformInfo = self._AutoGenObject.PlatformInfo\r
422\r
423 self.ResultFileList = []\r
424 self.IntermediateDirectoryList = ["$(DEBUG_DIR)", "$(OUTPUT_DIR)"]\r
425\r
f51461c8
LG
426 self.FileBuildTargetList = [] # [(src, target string)]\r
427 self.BuildTargetList = [] # [target string]\r
428 self.PendingBuildTargetList = [] # [FileBuildRule objects]\r
429 self.CommonFileDependency = []\r
430 self.FileListMacros = {}\r
431 self.ListFileMacros = {}\r
35c2af00 432 self.ObjTargetDict = OrderedDict()\r
f51461c8 433 self.FileCache = {}\r
f51461c8
LG
434 self.LibraryBuildCommandList = []\r
435 self.LibraryFileList = []\r
436 self.LibraryMakefileList = []\r
437 self.LibraryBuildDirectoryList = []\r
438 self.SystemLibraryList = []\r
9006a2c6 439 self.Macros = OrderedDict()\r
f51461c8
LG
440 self.Macros["OUTPUT_DIR" ] = self._AutoGenObject.Macros["OUTPUT_DIR"]\r
441 self.Macros["DEBUG_DIR" ] = self._AutoGenObject.Macros["DEBUG_DIR"]\r
442 self.Macros["MODULE_BUILD_DIR"] = self._AutoGenObject.Macros["MODULE_BUILD_DIR"]\r
443 self.Macros["BIN_DIR" ] = self._AutoGenObject.Macros["BIN_DIR"]\r
444 self.Macros["BUILD_DIR" ] = self._AutoGenObject.Macros["BUILD_DIR"]\r
445 self.Macros["WORKSPACE" ] = self._AutoGenObject.Macros["WORKSPACE"]\r
37de70b7
YZ
446 self.Macros["FFS_OUTPUT_DIR" ] = self._AutoGenObject.Macros["FFS_OUTPUT_DIR"]\r
447 self.GenFfsList = ModuleAutoGen.GenFfsList\r
448 self.MacroList = ['FFS_OUTPUT_DIR', 'MODULE_GUID', 'OUTPUT_DIR']\r
449 self.FfsOutputFileList = []\r
f51461c8
LG
450\r
451 # Compose a dict object containing information used to do replacement in template\r
4c92c81d
CJ
452 @property\r
453 def _TemplateDict(self):\r
f51461c8
LG
454 if self._FileType not in self._SEP_:\r
455 EdkLogger.error("build", PARAMETER_INVALID, "Invalid Makefile type [%s]" % self._FileType,\r
456 ExtraData="[%s]" % str(self._AutoGenObject))\r
7c12d613 457 MyAgo = self._AutoGenObject\r
f51461c8
LG
458 Separator = self._SEP_[self._FileType]\r
459\r
460 # break build if no source files and binary files are found\r
7c12d613 461 if len(MyAgo.SourceFileList) == 0 and len(MyAgo.BinaryFileList) == 0:\r
f51461c8 462 EdkLogger.error("build", AUTOGEN_ERROR, "No files to be built in module [%s, %s, %s]"\r
7c12d613
JC
463 % (MyAgo.BuildTarget, MyAgo.ToolChain, MyAgo.Arch),\r
464 ExtraData="[%s]" % str(MyAgo))\r
f51461c8
LG
465\r
466 # convert dependent libraries to build command\r
467 self.ProcessDependentLibrary()\r
7c12d613
JC
468 if len(MyAgo.Module.ModuleEntryPointList) > 0:\r
469 ModuleEntryPoint = MyAgo.Module.ModuleEntryPointList[0]\r
f51461c8
LG
470 else:\r
471 ModuleEntryPoint = "_ModuleEntryPoint"\r
472\r
82292501 473 ArchEntryPoint = ModuleEntryPoint\r
f51461c8 474\r
7c12d613 475 if MyAgo.Arch == "EBC":\r
f51461c8
LG
476 # EBC compiler always use "EfiStart" as entry point. Only applies to EdkII modules\r
477 ImageEntryPoint = "EfiStart"\r
f51461c8
LG
478 else:\r
479 # EdkII modules always use "_ModuleEntryPoint" as entry point\r
480 ImageEntryPoint = "_ModuleEntryPoint"\r
481\r
3a041437 482 for k, v in MyAgo.Module.Defines.items():\r
7c12d613
JC
483 if k not in MyAgo.Macros:\r
484 MyAgo.Macros[k] = v\r
3570e332 485\r
7c12d613
JC
486 if 'MODULE_ENTRY_POINT' not in MyAgo.Macros:\r
487 MyAgo.Macros['MODULE_ENTRY_POINT'] = ModuleEntryPoint\r
488 if 'ARCH_ENTRY_POINT' not in MyAgo.Macros:\r
489 MyAgo.Macros['ARCH_ENTRY_POINT'] = ArchEntryPoint\r
490 if 'IMAGE_ENTRY_POINT' not in MyAgo.Macros:\r
491 MyAgo.Macros['IMAGE_ENTRY_POINT'] = ImageEntryPoint\r
3570e332 492\r
9ccb26bc 493 PCI_COMPRESS_Flag = False\r
3a041437 494 for k, v in MyAgo.Module.Defines.items():\r
9ccb26bc
YZ
495 if 'PCI_COMPRESS' == k and 'TRUE' == v:\r
496 PCI_COMPRESS_Flag = True\r
497\r
f51461c8
LG
498 # tools definitions\r
499 ToolsDef = []\r
7c12d613
JC
500 IncPrefix = self._INC_FLAG_[MyAgo.ToolChainFamily]\r
501 for Tool in MyAgo.BuildOption:\r
502 for Attr in MyAgo.BuildOption[Tool]:\r
503 Value = MyAgo.BuildOption[Tool][Attr]\r
f51461c8
LG
504 if Attr == "FAMILY":\r
505 continue\r
506 elif Attr == "PATH":\r
507 ToolsDef.append("%s = %s" % (Tool, Value))\r
508 else:\r
509 # Don't generate MAKE_FLAGS in makefile. It's put in environment variable.\r
510 if Tool == "MAKE":\r
511 continue\r
512 # Remove duplicated include path, if any\r
513 if Attr == "FLAGS":\r
7c12d613 514 Value = RemoveDupOption(Value, IncPrefix, MyAgo.IncludePathList)\r
05217d21
FZ
515 if self._AutoGenObject.BuildRuleFamily == TAB_COMPILER_MSFT and Tool == 'CC' and '/GM' in Value:\r
516 Value = Value.replace(' /MP', '')\r
517 MyAgo.BuildOption[Tool][Attr] = Value\r
9ccb26bc
YZ
518 if Tool == "OPTROM" and PCI_COMPRESS_Flag:\r
519 ValueList = Value.split()\r
520 if ValueList:\r
521 for i, v in enumerate(ValueList):\r
522 if '-e' == v:\r
523 ValueList[i] = '-ec'\r
524 Value = ' '.join(ValueList)\r
525\r
f51461c8
LG
526 ToolsDef.append("%s_%s = %s" % (Tool, Attr, Value))\r
527 ToolsDef.append("")\r
528\r
725cdb8f
YZ
529 # generate the Response file and Response flag\r
530 RespDict = self.CommandExceedLimit()\r
7c12d613 531 RespFileList = os.path.join(MyAgo.OutputDir, 'respfilelist.txt')\r
725cdb8f
YZ
532 if RespDict:\r
533 RespFileListContent = ''\r
9eb87141 534 for Resp in RespDict:\r
7c12d613 535 RespFile = os.path.join(MyAgo.OutputDir, str(Resp).lower() + '.txt')\r
3570e332
YZ
536 StrList = RespDict[Resp].split(' ')\r
537 UnexpandMacro = []\r
538 NewStr = []\r
539 for Str in StrList:\r
540 if '$' in Str:\r
541 UnexpandMacro.append(Str)\r
542 else:\r
543 NewStr.append(Str)\r
544 UnexpandMacroStr = ' '.join(UnexpandMacro)\r
545 NewRespStr = ' '.join(NewStr)\r
546 SaveFileOnChange(RespFile, NewRespStr, False)\r
547 ToolsDef.append("%s = %s" % (Resp, UnexpandMacroStr + ' @' + RespFile))\r
2c2bb053
ZF
548 RespFileListContent += '@' + RespFile + TAB_LINE_BREAK\r
549 RespFileListContent += NewRespStr + TAB_LINE_BREAK\r
725cdb8f
YZ
550 SaveFileOnChange(RespFileList, RespFileListContent, False)\r
551 else:\r
552 if os.path.exists(RespFileList):\r
553 os.remove(RespFileList)\r
554\r
f51461c8 555 # convert source files and binary files to build targets\r
7c12d613
JC
556 self.ResultFileList = [str(T.Target) for T in MyAgo.CodaTargetList]\r
557 if len(self.ResultFileList) == 0 and len(MyAgo.SourceFileList) != 0:\r
f51461c8 558 EdkLogger.error("build", AUTOGEN_ERROR, "Nothing to build",\r
7c12d613 559 ExtraData="[%s]" % str(MyAgo))\r
f51461c8
LG
560\r
561 self.ProcessBuildTargetList()\r
37de70b7 562 self.ParserGenerateFfsCmd()\r
f51461c8
LG
563\r
564 # Generate macros used to represent input files\r
565 FileMacroList = [] # macro name = file list\r
566 for FileListMacro in self.FileListMacros:\r
567 FileMacro = self._FILE_MACRO_TEMPLATE.Replace(\r
568 {\r
569 "macro_name" : FileListMacro,\r
570 "source_file" : self.FileListMacros[FileListMacro]\r
571 }\r
572 )\r
573 FileMacroList.append(FileMacro)\r
574\r
575 # INC_LIST is special\r
576 FileMacro = ""\r
577 IncludePathList = []\r
7c12d613 578 for P in MyAgo.IncludePathList:\r
47fea6af 579 IncludePathList.append(IncPrefix + self.PlaceMacro(P, self.Macros))\r
f51461c8 580 if FileBuildRule.INC_LIST_MACRO in self.ListFileMacros:\r
47fea6af 581 self.ListFileMacros[FileBuildRule.INC_LIST_MACRO].append(IncPrefix + P)\r
f51461c8
LG
582 FileMacro += self._FILE_MACRO_TEMPLATE.Replace(\r
583 {\r
584 "macro_name" : "INC",\r
585 "source_file" : IncludePathList\r
586 }\r
587 )\r
588 FileMacroList.append(FileMacro)\r
073a76e6
ZF
589 # Add support when compiling .nasm source files\r
590 for File in self.FileCache.keys():\r
591 if not str(File).endswith('.nasm'):\r
592 continue\r
593 IncludePathList = []\r
594 for P in MyAgo.IncludePathList:\r
595 IncludePath = self._INC_FLAG_['NASM'] + self.PlaceMacro(P, self.Macros)\r
596 if IncludePath.endswith(os.sep):\r
597 IncludePath = IncludePath.rstrip(os.sep)\r
598 # When compiling .nasm files, need to add a literal backslash at each path\r
599 # To specify a literal backslash at the end of the line, precede it with a caret (^)\r
600 if P == MyAgo.IncludePathList[-1] and os.sep == '\\':\r
601 IncludePath = ''.join([IncludePath, '^', os.sep])\r
602 else:\r
603 IncludePath = os.path.join(IncludePath, '')\r
604 IncludePathList.append(IncludePath)\r
605 FileMacroList.append(self._FILE_MACRO_TEMPLATE.Replace({"macro_name": "NASM_INC", "source_file": IncludePathList}))\r
606 break\r
f51461c8
LG
607\r
608 # Generate macros used to represent files containing list of input files\r
609 for ListFileMacro in self.ListFileMacros:\r
7c12d613 610 ListFileName = os.path.join(MyAgo.OutputDir, "%s.lst" % ListFileMacro.lower()[:len(ListFileMacro) - 5])\r
f51461c8
LG
611 FileMacroList.append("%s = %s" % (ListFileMacro, ListFileName))\r
612 SaveFileOnChange(\r
613 ListFileName,\r
614 "\n".join(self.ListFileMacros[ListFileMacro]),\r
615 False\r
616 )\r
617\r
05217d21
FZ
618 # Generate objlist used to create .obj file\r
619 for Type in self.ObjTargetDict:\r
620 NewLine = ' '.join(list(self.ObjTargetDict[Type]))\r
621 FileMacroList.append("OBJLIST_%s = %s" % (list(self.ObjTargetDict.keys()).index(Type), NewLine))\r
622\r
f51461c8
LG
623 BcTargetList = []\r
624\r
625 MakefileName = self._FILE_NAME_[self._FileType]\r
626 LibraryMakeCommandList = []\r
627 for D in self.LibraryBuildDirectoryList:\r
628 Command = self._MAKE_TEMPLATE_[self._FileType] % {"file":os.path.join(D, MakefileName)}\r
629 LibraryMakeCommandList.append(Command)\r
630\r
7c12d613 631 package_rel_dir = MyAgo.SourceDir\r
b442ad5c
YL
632 current_dir = self.Macros["WORKSPACE"]\r
633 found = False\r
634 while not found and os.sep in package_rel_dir:\r
635 index = package_rel_dir.index(os.sep)\r
05cc51ad 636 current_dir = mws.join(current_dir, package_rel_dir[:index])\r
570ae1eb
YZ
637 if os.path.exists(current_dir):\r
638 for fl in os.listdir(current_dir):\r
639 if fl.endswith('.dec'):\r
640 found = True\r
641 break\r
b442ad5c 642 package_rel_dir = package_rel_dir[index + 1:]\r
97fa0ee9 643\r
f51461c8
LG
644 MakefileTemplateDict = {\r
645 "makefile_header" : self._FILE_HEADER_[self._FileType],\r
646 "makefile_path" : os.path.join("$(MODULE_BUILD_DIR)", MakefileName),\r
647 "makefile_name" : MakefileName,\r
648 "platform_name" : self.PlatformInfo.Name,\r
649 "platform_guid" : self.PlatformInfo.Guid,\r
650 "platform_version" : self.PlatformInfo.Version,\r
651 "platform_relative_directory": self.PlatformInfo.SourceDir,\r
652 "platform_output_directory" : self.PlatformInfo.OutputDir,\r
7c12d613
JC
653 "ffs_output_directory" : MyAgo.Macros["FFS_OUTPUT_DIR"],\r
654 "platform_dir" : MyAgo.Macros["PLATFORM_DIR"],\r
655\r
656 "module_name" : MyAgo.Name,\r
657 "module_guid" : MyAgo.Guid,\r
658 "module_name_guid" : MyAgo.UniqueBaseName,\r
659 "module_version" : MyAgo.Version,\r
660 "module_type" : MyAgo.ModuleType,\r
661 "module_file" : MyAgo.MetaFile.Name,\r
662 "module_file_base_name" : MyAgo.MetaFile.BaseName,\r
663 "module_relative_directory" : MyAgo.SourceDir,\r
664 "module_dir" : mws.join (self.Macros["WORKSPACE"], MyAgo.SourceDir),\r
97fa0ee9 665 "package_relative_directory": package_rel_dir,\r
3a041437 666 "module_extra_defines" : ["%s = %s" % (k, v) for k, v in MyAgo.Module.Defines.items()],\r
f51461c8 667\r
7c12d613
JC
668 "architecture" : MyAgo.Arch,\r
669 "toolchain_tag" : MyAgo.ToolChain,\r
670 "build_target" : MyAgo.BuildTarget,\r
f51461c8
LG
671\r
672 "platform_build_directory" : self.PlatformInfo.BuildDir,\r
7c12d613
JC
673 "module_build_directory" : MyAgo.BuildDir,\r
674 "module_output_directory" : MyAgo.OutputDir,\r
675 "module_debug_directory" : MyAgo.DebugDir,\r
f51461c8
LG
676\r
677 "separator" : Separator,\r
678 "module_tool_definitions" : ToolsDef,\r
679\r
f8d11e5a
FB
680 "shell_command_code" : list(self._SHELL_CMD_[self._FileType].keys()),\r
681 "shell_command" : list(self._SHELL_CMD_[self._FileType].values()),\r
f51461c8
LG
682\r
683 "module_entry_point" : ModuleEntryPoint,\r
684 "image_entry_point" : ImageEntryPoint,\r
685 "arch_entry_point" : ArchEntryPoint,\r
686 "remaining_build_target" : self.ResultFileList,\r
687 "common_dependency_file" : self.CommonFileDependency,\r
688 "create_directory_command" : self.GetCreateDirectoryCommand(self.IntermediateDirectoryList),\r
689 "clean_command" : self.GetRemoveDirectoryCommand(["$(OUTPUT_DIR)"]),\r
690 "cleanall_command" : self.GetRemoveDirectoryCommand(["$(DEBUG_DIR)", "$(OUTPUT_DIR)"]),\r
691 "dependent_library_build_directory" : self.LibraryBuildDirectoryList,\r
692 "library_build_command" : LibraryMakeCommandList,\r
693 "file_macro" : FileMacroList,\r
694 "file_build_target" : self.BuildTargetList,\r
695 "backward_compatible_target": BcTargetList,\r
696 }\r
697\r
698 return MakefileTemplateDict\r
699\r
37de70b7
YZ
700 def ParserGenerateFfsCmd(self):\r
701 #Add Ffs cmd to self.BuildTargetList\r
702 OutputFile = ''\r
703 DepsFileList = []\r
704\r
705 for Cmd in self.GenFfsList:\r
706 if Cmd[2]:\r
707 for CopyCmd in Cmd[2]:\r
708 Src, Dst = CopyCmd\r
709 Src = self.ReplaceMacro(Src)\r
710 Dst = self.ReplaceMacro(Dst)\r
711 if Dst not in self.ResultFileList:\r
caf74495 712 self.ResultFileList.append(Dst)\r
37de70b7
YZ
713 if '%s :' %(Dst) not in self.BuildTargetList:\r
714 self.BuildTargetList.append("%s :" %(Dst))\r
715 self.BuildTargetList.append('\t' + self._CP_TEMPLATE_[self._FileType] %{'Src': Src, 'Dst': Dst})\r
716\r
717 FfsCmdList = Cmd[0]\r
718 for index, Str in enumerate(FfsCmdList):\r
719 if '-o' == Str:\r
720 OutputFile = FfsCmdList[index + 1]\r
b1e27d17 721 if '-i' == Str or "-oi" == Str:\r
37de70b7
YZ
722 if DepsFileList == []:\r
723 DepsFileList = [FfsCmdList[index + 1]]\r
724 else:\r
725 DepsFileList.append(FfsCmdList[index + 1])\r
726 DepsFileString = ' '.join(DepsFileList).strip()\r
727 if DepsFileString == '':\r
728 continue\r
729 OutputFile = self.ReplaceMacro(OutputFile)\r
caf74495 730 self.ResultFileList.append(OutputFile)\r
37de70b7
YZ
731 DepsFileString = self.ReplaceMacro(DepsFileString)\r
732 self.BuildTargetList.append('%s : %s' % (OutputFile, DepsFileString))\r
733 CmdString = ' '.join(FfsCmdList).strip()\r
734 CmdString = self.ReplaceMacro(CmdString)\r
735 self.BuildTargetList.append('\t%s' % CmdString)\r
736\r
737 self.ParseSecCmd(DepsFileList, Cmd[1])\r
738 for SecOutputFile, SecDepsFile, SecCmd in self.FfsOutputFileList :\r
739 self.BuildTargetList.append('%s : %s' % (self.ReplaceMacro(SecOutputFile), self.ReplaceMacro(SecDepsFile)))\r
740 self.BuildTargetList.append('\t%s' % self.ReplaceMacro(SecCmd))\r
741 self.FfsOutputFileList = []\r
742\r
743 def ParseSecCmd(self, OutputFileList, CmdTuple):\r
744 for OutputFile in OutputFileList:\r
745 for SecCmdStr in CmdTuple:\r
746 SecDepsFileList = []\r
747 SecCmdList = SecCmdStr.split()\r
748 CmdName = SecCmdList[0]\r
749 for index, CmdItem in enumerate(SecCmdList):\r
750 if '-o' == CmdItem and OutputFile == SecCmdList[index + 1]:\r
751 index = index + 1\r
752 while index + 1 < len(SecCmdList):\r
753 if not SecCmdList[index+1].startswith('-'):\r
754 SecDepsFileList.append(SecCmdList[index + 1])\r
755 index = index + 1\r
756 if CmdName == 'Trim':\r
757 SecDepsFileList.append(os.path.join('$(DEBUG_DIR)', os.path.basename(OutputFile).replace('offset', 'efi')))\r
758 if OutputFile.endswith('.ui') or OutputFile.endswith('.ver'):\r
ccaa7754 759 SecDepsFileList.append(os.path.join('$(MODULE_DIR)', '$(MODULE_FILE)'))\r
37de70b7
YZ
760 self.FfsOutputFileList.append((OutputFile, ' '.join(SecDepsFileList), SecCmdStr))\r
761 if len(SecDepsFileList) > 0:\r
762 self.ParseSecCmd(SecDepsFileList, CmdTuple)\r
763 break\r
764 else:\r
765 continue\r
766\r
767 def ReplaceMacro(self, str):\r
768 for Macro in self.MacroList:\r
769 if self._AutoGenObject.Macros[Macro] and self._AutoGenObject.Macros[Macro] in str:\r
770 str = str.replace(self._AutoGenObject.Macros[Macro], '$(' + Macro + ')')\r
771 return str\r
772\r
725cdb8f
YZ
773 def CommandExceedLimit(self):\r
774 FlagDict = {\r
775 'CC' : { 'Macro' : '$(CC_FLAGS)', 'Value' : False},\r
776 'PP' : { 'Macro' : '$(PP_FLAGS)', 'Value' : False},\r
777 'APP' : { 'Macro' : '$(APP_FLAGS)', 'Value' : False},\r
778 'ASLPP' : { 'Macro' : '$(ASLPP_FLAGS)', 'Value' : False},\r
779 'VFRPP' : { 'Macro' : '$(VFRPP_FLAGS)', 'Value' : False},\r
780 'ASM' : { 'Macro' : '$(ASM_FLAGS)', 'Value' : False},\r
781 'ASLCC' : { 'Macro' : '$(ASLCC_FLAGS)', 'Value' : False},\r
782 }\r
783\r
784 RespDict = {}\r
785 FileTypeList = []\r
786 IncPrefix = self._INC_FLAG_[self._AutoGenObject.ToolChainFamily]\r
787\r
788 # base on the source files to decide the file type\r
789 for File in self._AutoGenObject.SourceFileList:\r
790 for type in self._AutoGenObject.FileTypes:\r
791 if File in self._AutoGenObject.FileTypes[type]:\r
792 if type not in FileTypeList:\r
793 FileTypeList.append(type)\r
794\r
795 # calculate the command-line length\r
796 if FileTypeList:\r
797 for type in FileTypeList:\r
798 BuildTargets = self._AutoGenObject.BuildRules[type].BuildTargets\r
799 for Target in BuildTargets:\r
800 CommandList = BuildTargets[Target].Commands\r
801 for SingleCommand in CommandList:\r
802 Tool = ''\r
803 SingleCommandLength = len(SingleCommand)\r
804 SingleCommandList = SingleCommand.split()\r
805 if len(SingleCommandList) > 0:\r
9eb87141 806 for Flag in FlagDict:\r
725cdb8f
YZ
807 if '$('+ Flag +')' in SingleCommandList[0]:\r
808 Tool = Flag\r
809 break\r
810 if Tool:\r
b23414f6 811 if 'PATH' not in self._AutoGenObject.BuildOption[Tool]:\r
70d0a754 812 EdkLogger.error("build", AUTOGEN_ERROR, "%s_PATH doesn't exist in %s ToolChain and %s Arch." %(Tool, self._AutoGenObject.ToolChain, self._AutoGenObject.Arch), ExtraData="[%s]" % str(self._AutoGenObject))\r
b23414f6 813 SingleCommandLength += len(self._AutoGenObject.BuildOption[Tool]['PATH'])\r
725cdb8f
YZ
814 for item in SingleCommandList[1:]:\r
815 if FlagDict[Tool]['Macro'] in item:\r
b23414f6 816 if 'FLAGS' not in self._AutoGenObject.BuildOption[Tool]:\r
70d0a754 817 EdkLogger.error("build", AUTOGEN_ERROR, "%s_FLAGS doesn't exist in %s ToolChain and %s Arch." %(Tool, self._AutoGenObject.ToolChain, self._AutoGenObject.Arch), ExtraData="[%s]" % str(self._AutoGenObject))\r
b23414f6 818 Str = self._AutoGenObject.BuildOption[Tool]['FLAGS']\r
9eb87141 819 for Option in self._AutoGenObject.BuildOption:\r
3570e332
YZ
820 for Attr in self._AutoGenObject.BuildOption[Option]:\r
821 if Str.find(Option + '_' + Attr) != -1:\r
822 Str = Str.replace('$(' + Option + '_' + Attr + ')', self._AutoGenObject.BuildOption[Option][Attr])\r
725cdb8f 823 while(Str.find('$(') != -1):\r
9eb87141 824 for macro in self._AutoGenObject.Macros:\r
725cdb8f
YZ
825 MacroName = '$('+ macro + ')'\r
826 if (Str.find(MacroName) != -1):\r
827 Str = Str.replace(MacroName, self._AutoGenObject.Macros[macro])\r
828 break\r
829 else:\r
3570e332 830 break\r
725cdb8f
YZ
831 SingleCommandLength += len(Str)\r
832 elif '$(INC)' in item:\r
b23414f6 833 SingleCommandLength += self._AutoGenObject.IncludePathLength + len(IncPrefix) * len(self._AutoGenObject.IncludePathList)\r
725cdb8f
YZ
834 elif item.find('$(') != -1:\r
835 Str = item\r
9eb87141 836 for Option in self._AutoGenObject.BuildOption:\r
725cdb8f
YZ
837 for Attr in self._AutoGenObject.BuildOption[Option]:\r
838 if Str.find(Option + '_' + Attr) != -1:\r
839 Str = Str.replace('$(' + Option + '_' + Attr + ')', self._AutoGenObject.BuildOption[Option][Attr])\r
840 while(Str.find('$(') != -1):\r
9eb87141 841 for macro in self._AutoGenObject.Macros:\r
725cdb8f
YZ
842 MacroName = '$('+ macro + ')'\r
843 if (Str.find(MacroName) != -1):\r
844 Str = Str.replace(MacroName, self._AutoGenObject.Macros[macro])\r
845 break\r
846 else:\r
3570e332 847 break\r
725cdb8f
YZ
848 SingleCommandLength += len(Str)\r
849\r
850 if SingleCommandLength > GlobalData.gCommandMaxLength:\r
851 FlagDict[Tool]['Value'] = True\r
852\r
853 # generate the response file content by combine the FLAGS and INC\r
9eb87141 854 for Flag in FlagDict:\r
725cdb8f
YZ
855 if FlagDict[Flag]['Value']:\r
856 Key = Flag + '_RESP'\r
857 RespMacro = FlagDict[Flag]['Macro'].replace('FLAGS', 'RESP')\r
858 Value = self._AutoGenObject.BuildOption[Flag]['FLAGS']\r
b23414f6 859 for inc in self._AutoGenObject.IncludePathList:\r
725cdb8f 860 Value += ' ' + IncPrefix + inc\r
9eb87141 861 for Option in self._AutoGenObject.BuildOption:\r
3570e332
YZ
862 for Attr in self._AutoGenObject.BuildOption[Option]:\r
863 if Value.find(Option + '_' + Attr) != -1:\r
864 Value = Value.replace('$(' + Option + '_' + Attr + ')', self._AutoGenObject.BuildOption[Option][Attr])\r
725cdb8f 865 while (Value.find('$(') != -1):\r
9eb87141 866 for macro in self._AutoGenObject.Macros:\r
725cdb8f
YZ
867 MacroName = '$('+ macro + ')'\r
868 if (Value.find(MacroName) != -1):\r
869 Value = Value.replace(MacroName, self._AutoGenObject.Macros[macro])\r
870 break\r
871 else:\r
3570e332 872 break\r
669b6cc6
YZ
873\r
874 if self._AutoGenObject.ToolChainFamily == 'GCC':\r
875 RespDict[Key] = Value.replace('\\', '/')\r
876 else:\r
877 RespDict[Key] = Value\r
725cdb8f
YZ
878 for Target in BuildTargets:\r
879 for i, SingleCommand in enumerate(BuildTargets[Target].Commands):\r
880 if FlagDict[Flag]['Macro'] in SingleCommand:\r
ccaa7754 881 BuildTargets[Target].Commands[i] = SingleCommand.replace('$(INC)', '').replace(FlagDict[Flag]['Macro'], RespMacro)\r
725cdb8f
YZ
882 return RespDict\r
883\r
f51461c8
LG
884 def ProcessBuildTargetList(self):\r
885 #\r
886 # Search dependency file list for each source file\r
887 #\r
888 ForceIncludedFile = []\r
889 for File in self._AutoGenObject.AutoGenFileList:\r
890 if File.Ext == '.h':\r
891 ForceIncludedFile.append(File)\r
892 SourceFileList = []\r
a3a47370 893 OutPutFileList = []\r
f51461c8
LG
894 for Target in self._AutoGenObject.IntroTargetList:\r
895 SourceFileList.extend(Target.Inputs)\r
a3a47370
YZ
896 OutPutFileList.extend(Target.Outputs)\r
897\r
898 if OutPutFileList:\r
899 for Item in OutPutFileList:\r
900 if Item in SourceFileList:\r
901 SourceFileList.remove(Item)\r
f51461c8 902\r
0f78fd73 903 FileDependencyDict = self.GetFileDependency(\r
f51461c8
LG
904 SourceFileList,\r
905 ForceIncludedFile,\r
906 self._AutoGenObject.IncludePathList + self._AutoGenObject.BuildOptionIncPathList\r
907 )\r
1fa6699e
RC
908\r
909 # Check if header files are listed in metafile\r
910 # Get a list of unique module header source files from MetaFile\r
911 headerFilesInMetaFileSet = set()\r
912 for aFile in self._AutoGenObject.SourceFileList:\r
913 aFileName = str(aFile)\r
914 if not aFileName.endswith('.h'):\r
915 continue\r
916 headerFilesInMetaFileSet.add(aFileName.lower())\r
917\r
918 # Get a list of unique module autogen files\r
919 localAutoGenFileSet = set()\r
920 for aFile in self._AutoGenObject.AutoGenFileList:\r
921 localAutoGenFileSet.add(str(aFile).lower())\r
922\r
923 # Get a list of unique module dependency header files\r
924 # Exclude autogen files and files not in the source directory\r
925 headerFileDependencySet = set()\r
926 localSourceDir = str(self._AutoGenObject.SourceDir).lower()\r
927 for Dependency in FileDependencyDict.values():\r
928 for aFile in Dependency:\r
929 aFileName = str(aFile).lower()\r
930 if not aFileName.endswith('.h'):\r
931 continue\r
932 if aFileName in localAutoGenFileSet:\r
933 continue\r
934 if localSourceDir not in aFileName:\r
935 continue\r
936 headerFileDependencySet.add(aFileName)\r
937\r
938 # Check if a module dependency header file is missing from the module's MetaFile\r
939 for aFile in headerFileDependencySet:\r
940 if aFile in headerFilesInMetaFileSet:\r
941 continue\r
942 EdkLogger.warn("build","Module MetaFile [Sources] is missing local header!",\r
943 ExtraData = "Local Header: " + aFile + " not found in " + self._AutoGenObject.MetaFile.Path\r
944 )\r
945\r
f51461c8 946 DepSet = None\r
0f78fd73
JC
947 for File,Dependency in FileDependencyDict.items():\r
948 if not Dependency:\r
949 FileDependencyDict[File] = ['$(FORCE_REBUILD)']\r
f51461c8 950 continue\r
c17956e0 951\r
0f78fd73 952 self._AutoGenObject.AutoGenDepSet |= set(Dependency)\r
c17956e0 953\r
f51461c8
LG
954 # skip non-C files\r
955 if File.Ext not in [".c", ".C"] or File.Name == "AutoGen.c":\r
956 continue\r
4231a819 957 elif DepSet is None:\r
0f78fd73 958 DepSet = set(Dependency)\r
f51461c8 959 else:\r
0f78fd73 960 DepSet &= set(Dependency)\r
f51461c8 961 # in case nothing in SourceFileList\r
4231a819 962 if DepSet is None:\r
f51461c8
LG
963 DepSet = set()\r
964 #\r
965 # Extract common files list in the dependency files\r
966 #\r
1ccc4d89 967 for File in DepSet:\r
f51461c8
LG
968 self.CommonFileDependency.append(self.PlaceMacro(File.Path, self.Macros))\r
969\r
05217d21
FZ
970 CmdSumDict = {}\r
971 CmdTargetDict = {}\r
972 CmdCppDict = {}\r
973 DependencyDict = FileDependencyDict.copy()\r
0f78fd73 974 for File in FileDependencyDict:\r
f51461c8
LG
975 # skip non-C files\r
976 if File.Ext not in [".c", ".C"] or File.Name == "AutoGen.c":\r
977 continue\r
0f78fd73 978 NewDepSet = set(FileDependencyDict[File])\r
f51461c8 979 NewDepSet -= DepSet\r
1ccc4d89 980 FileDependencyDict[File] = ["$(COMMON_DEPS)"] + list(NewDepSet)\r
05217d21 981 DependencyDict[File] = list(NewDepSet)\r
f51461c8
LG
982\r
983 # Convert target description object to target string in makefile\r
35c2af00
FZ
984 if self._AutoGenObject.BuildRuleFamily == TAB_COMPILER_MSFT and TAB_C_CODE_FILE in self._AutoGenObject.Targets:\r
985 for T in self._AutoGenObject.Targets[TAB_C_CODE_FILE]:\r
986 NewFile = self.PlaceMacro(str(T), self.Macros)\r
987 if not self.ObjTargetDict.get(T.Target.SubDir):\r
988 self.ObjTargetDict[T.Target.SubDir] = set()\r
989 self.ObjTargetDict[T.Target.SubDir].add(NewFile)\r
f51461c8 990 for Type in self._AutoGenObject.Targets:\r
1ccc4d89 991 for T in self._AutoGenObject.Targets[Type]:\r
f51461c8
LG
992 # Generate related macros if needed\r
993 if T.GenFileListMacro and T.FileListMacro not in self.FileListMacros:\r
994 self.FileListMacros[T.FileListMacro] = []\r
995 if T.GenListFile and T.ListFileMacro not in self.ListFileMacros:\r
996 self.ListFileMacros[T.ListFileMacro] = []\r
997 if T.GenIncListFile and T.IncListFileMacro not in self.ListFileMacros:\r
998 self.ListFileMacros[T.IncListFileMacro] = []\r
999\r
1000 Deps = []\r
05217d21 1001 CCodeDeps = []\r
f51461c8
LG
1002 # Add force-dependencies\r
1003 for Dep in T.Dependencies:\r
1004 Deps.append(self.PlaceMacro(str(Dep), self.Macros))\r
05217d21
FZ
1005 if Dep != '$(MAKE_FILE)':\r
1006 CCodeDeps.append(self.PlaceMacro(str(Dep), self.Macros))\r
f51461c8 1007 # Add inclusion-dependencies\r
0f78fd73
JC
1008 if len(T.Inputs) == 1 and T.Inputs[0] in FileDependencyDict:\r
1009 for F in FileDependencyDict[T.Inputs[0]]:\r
f51461c8
LG
1010 Deps.append(self.PlaceMacro(str(F), self.Macros))\r
1011 # Add source-dependencies\r
1012 for F in T.Inputs:\r
1013 NewFile = self.PlaceMacro(str(F), self.Macros)\r
1014 # In order to use file list macro as dependency\r
1015 if T.GenListFile:\r
fb0b35e0 1016 # gnu tools need forward slash path separator, even on Windows\r
285a1754 1017 self.ListFileMacros[T.ListFileMacro].append(str(F).replace ('\\', '/'))\r
f51461c8
LG
1018 self.FileListMacros[T.FileListMacro].append(NewFile)\r
1019 elif T.GenFileListMacro:\r
1020 self.FileListMacros[T.FileListMacro].append(NewFile)\r
1021 else:\r
1022 Deps.append(NewFile)\r
1023\r
1024 # Use file list macro as dependency\r
1025 if T.GenFileListMacro:\r
1026 Deps.append("$(%s)" % T.FileListMacro)\r
1c62af9e
YZ
1027 if Type in [TAB_OBJECT_FILE, TAB_STATIC_LIBRARY]:\r
1028 Deps.append("$(%s)" % T.ListFileMacro)\r
f51461c8 1029\r
05217d21
FZ
1030 if self._AutoGenObject.BuildRuleFamily == TAB_COMPILER_MSFT and Type == TAB_C_CODE_FILE:\r
1031 T, CmdTarget, CmdTargetDict, CmdCppDict = self.ParserCCodeFile(T, Type, CmdSumDict, CmdTargetDict, CmdCppDict, DependencyDict)\r
1032 TargetDict = {"target": self.PlaceMacro(T.Target.Path, self.Macros), "cmd": "\n\t".join(T.Commands),"deps": CCodeDeps}\r
1033 CmdLine = self._BUILD_TARGET_TEMPLATE.Replace(TargetDict).rstrip().replace('\t$(OBJLIST', '$(OBJLIST')\r
1034 if T.Commands:\r
1035 CmdLine = '%s%s' %(CmdLine, TAB_LINE_BREAK)\r
1036 if CCodeDeps or CmdLine:\r
1037 self.BuildTargetList.append(CmdLine)\r
1038 else:\r
1039 TargetDict = {"target": self.PlaceMacro(T.Target.Path, self.Macros), "cmd": "\n\t".join(T.Commands),"deps": Deps}\r
1040 self.BuildTargetList.append(self._BUILD_TARGET_TEMPLATE.Replace(TargetDict))\r
1041\r
1042 def ParserCCodeFile(self, T, Type, CmdSumDict, CmdTargetDict, CmdCppDict, DependencyDict):\r
1043 if not CmdSumDict:\r
1044 for item in self._AutoGenObject.Targets[Type]:\r
1045 CmdSumDict[item.Target.SubDir] = item.Target.BaseName\r
1046 for CppPath in item.Inputs:\r
1047 Path = self.PlaceMacro(CppPath.Path, self.Macros)\r
1048 if CmdCppDict.get(item.Target.SubDir):\r
1049 CmdCppDict[item.Target.SubDir].append(Path)\r
1050 else:\r
1051 CmdCppDict[item.Target.SubDir] = ['$(MAKE_FILE)', Path]\r
1052 if CppPath.Path in DependencyDict:\r
1053 for Temp in DependencyDict[CppPath.Path]:\r
1054 try:\r
1055 Path = self.PlaceMacro(Temp.Path, self.Macros)\r
1056 except:\r
1057 continue\r
1058 if Path not in (self.CommonFileDependency + CmdCppDict[item.Target.SubDir]):\r
1059 CmdCppDict[item.Target.SubDir].append(Path)\r
1060 if T.Commands:\r
1061 CommandList = T.Commands[:]\r
1062 for Item in CommandList[:]:\r
1063 SingleCommandList = Item.split()\r
c9b3fe15 1064 if len(SingleCommandList) > 0 and self.CheckCCCmd(SingleCommandList):\r
05217d21
FZ
1065 for Temp in SingleCommandList:\r
1066 if Temp.startswith('/Fo'):\r
1067 CmdSign = '%s%s' % (Temp.rsplit(TAB_SLASH, 1)[0], TAB_SLASH)\r
1068 break\r
1069 else: continue\r
1070 if CmdSign not in list(CmdTargetDict.keys()):\r
1071 CmdTargetDict[CmdSign] = Item.replace(Temp, CmdSign)\r
1072 else:\r
1073 CmdTargetDict[CmdSign] = "%s %s" % (CmdTargetDict[CmdSign], SingleCommandList[-1])\r
1074 Index = CommandList.index(Item)\r
1075 CommandList.pop(Index)\r
1076 if SingleCommandList[-1].endswith("%s%s.c" % (TAB_SLASH, CmdSumDict[CmdSign.lstrip('/Fo').rsplit(TAB_SLASH, 1)[0]])):\r
1077 Cpplist = CmdCppDict[T.Target.SubDir]\r
1078 Cpplist.insert(0, '$(OBJLIST_%d): $(COMMON_DEPS)' % list(self.ObjTargetDict.keys()).index(T.Target.SubDir))\r
1079 T.Commands[Index] = '%s\n\t%s' % (' \\\n\t'.join(Cpplist), CmdTargetDict[CmdSign])\r
1080 else:\r
1081 T.Commands.pop(Index)\r
1082 return T, CmdSumDict, CmdTargetDict, CmdCppDict\r
f51461c8 1083\r
c9b3fe15
BF
1084 def CheckCCCmd(self, CommandList):\r
1085 for cmd in CommandList:\r
1086 if '$(CC)' in cmd:\r
1087 return True\r
1088 return False\r
f51461c8
LG
1089 ## For creating makefile targets for dependent libraries\r
1090 def ProcessDependentLibrary(self):\r
1091 for LibraryAutoGen in self._AutoGenObject.LibraryAutoGenList:\r
db4d47fd 1092 if not LibraryAutoGen.IsBinaryModule and not LibraryAutoGen.CanSkipbyHash():\r
8832c79d 1093 self.LibraryBuildDirectoryList.append(self.PlaceMacro(LibraryAutoGen.BuildDir, self.Macros))\r
f51461c8
LG
1094\r
1095 ## Return a list containing source file's dependencies\r
1096 #\r
1097 # @param FileList The list of source files\r
1098 # @param ForceInculeList The list of files which will be included forcely\r
1099 # @param SearchPathList The list of search path\r
1100 #\r
1101 # @retval dict The mapping between source file path and its dependencies\r
1102 #\r
1103 def GetFileDependency(self, FileList, ForceInculeList, SearchPathList):\r
1104 Dependency = {}\r
1105 for F in FileList:\r
1106 Dependency[F] = self.GetDependencyList(F, ForceInculeList, SearchPathList)\r
1107 return Dependency\r
1108\r
1109 ## Find dependencies for one source file\r
1110 #\r
1111 # By searching recursively "#include" directive in file, find out all the\r
fb0b35e0 1112 # files needed by given source file. The dependencies will be only searched\r
f51461c8
LG
1113 # in given search path list.\r
1114 #\r
1115 # @param File The source file\r
1116 # @param ForceInculeList The list of files which will be included forcely\r
1117 # @param SearchPathList The list of search path\r
1118 #\r
1119 # @retval list The list of files the given source file depends on\r
1120 #\r
1121 def GetDependencyList(self, File, ForceList, SearchPathList):\r
1122 EdkLogger.debug(EdkLogger.DEBUG_1, "Try to get dependency files for %s" % File)\r
1123 FileStack = [File] + ForceList\r
1124 DependencySet = set()\r
1125\r
1126 if self._AutoGenObject.Arch not in gDependencyDatabase:\r
1127 gDependencyDatabase[self._AutoGenObject.Arch] = {}\r
1128 DepDb = gDependencyDatabase[self._AutoGenObject.Arch]\r
1129\r
1130 while len(FileStack) > 0:\r
1131 F = FileStack.pop()\r
1132\r
1133 FullPathDependList = []\r
1134 if F in self.FileCache:\r
1135 for CacheFile in self.FileCache[F]:\r
1136 FullPathDependList.append(CacheFile)\r
1137 if CacheFile not in DependencySet:\r
1138 FileStack.append(CacheFile)\r
1139 DependencySet.update(FullPathDependList)\r
1140 continue\r
1141\r
1142 CurrentFileDependencyList = []\r
1143 if F in DepDb:\r
1144 CurrentFileDependencyList = DepDb[F]\r
1145 else:\r
1146 try:\r
d943b0c3
FB
1147 Fd = open(F.Path, 'rb')\r
1148 FileContent = Fd.read()\r
1149 Fd.close()\r
5b0671c1 1150 except BaseException as X:\r
47fea6af 1151 EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData=F.Path + "\n\t" + str(X))\r
f51461c8
LG
1152 if len(FileContent) == 0:\r
1153 continue\r
f747640b
FB
1154 try:\r
1155 if FileContent[0] == 0xff or FileContent[0] == 0xfe:\r
1156 FileContent = FileContent.decode('utf-16')\r
1157 else:\r
1158 FileContent = FileContent.decode()\r
1159 except:\r
1160 # The file is not txt file. for example .mcb file\r
1161 continue\r
1ccc4d89 1162 IncludedFileList = gIncludePattern.findall(FileContent)\r
f51461c8
LG
1163\r
1164 for Inc in IncludedFileList:\r
1165 Inc = Inc.strip()\r
1166 # if there's macro used to reference header file, expand it\r
1167 HeaderList = gMacroPattern.findall(Inc)\r
1168 if len(HeaderList) == 1 and len(HeaderList[0]) == 2:\r
1169 HeaderType = HeaderList[0][0]\r
1170 HeaderKey = HeaderList[0][1]\r
1171 if HeaderType in gIncludeMacroConversion:\r
1172 Inc = gIncludeMacroConversion[HeaderType] % {"HeaderKey" : HeaderKey}\r
1173 else:\r
1174 # not known macro used in #include, always build the file by\r
1175 # returning a empty dependency\r
1176 self.FileCache[File] = []\r
1177 return []\r
1178 Inc = os.path.normpath(Inc)\r
1179 CurrentFileDependencyList.append(Inc)\r
1180 DepDb[F] = CurrentFileDependencyList\r
1181\r
1182 CurrentFilePath = F.Dir\r
1183 PathList = [CurrentFilePath] + SearchPathList\r
1184 for Inc in CurrentFileDependencyList:\r
1185 for SearchPath in PathList:\r
1186 FilePath = os.path.join(SearchPath, Inc)\r
1187 if FilePath in gIsFileMap:\r
1188 if not gIsFileMap[FilePath]:\r
1189 continue\r
1190 # If isfile is called too many times, the performance is slow down.\r
1191 elif not os.path.isfile(FilePath):\r
1192 gIsFileMap[FilePath] = False\r
1193 continue\r
1194 else:\r
1195 gIsFileMap[FilePath] = True\r
1196 FilePath = PathClass(FilePath)\r
1197 FullPathDependList.append(FilePath)\r
1198 if FilePath not in DependencySet:\r
1199 FileStack.append(FilePath)\r
1200 break\r
1201 else:\r
1202 EdkLogger.debug(EdkLogger.DEBUG_9, "%s included by %s was not found "\\r
1203 "in any given path:\n\t%s" % (Inc, F, "\n\t".join(SearchPathList)))\r
1204\r
1205 self.FileCache[F] = FullPathDependList\r
1206 DependencySet.update(FullPathDependList)\r
1207\r
1208 DependencySet.update(ForceList)\r
1209 if File in DependencySet:\r
1210 DependencySet.remove(File)\r
1ccc4d89 1211 DependencyList = list(DependencySet) # remove duplicate ones\r
f51461c8
LG
1212\r
1213 return DependencyList\r
1214\r
f51461c8
LG
1215## CustomMakefile class\r
1216#\r
1217# This class encapsules makefie and its generation for module. It uses template to generate\r
1218# the content of makefile. The content of makefile will be got from ModuleAutoGen object.\r
1219#\r
1220class CustomMakefile(BuildFile):\r
1221 ## template used to generate the makefile for module with custom makefile\r
1222 _TEMPLATE_ = TemplateString('''\\r
1223${makefile_header}\r
1224\r
1225#\r
1226# Platform Macro Definition\r
1227#\r
1228PLATFORM_NAME = ${platform_name}\r
1229PLATFORM_GUID = ${platform_guid}\r
1230PLATFORM_VERSION = ${platform_version}\r
1231PLATFORM_RELATIVE_DIR = ${platform_relative_directory}\r
7a5f1426 1232PLATFORM_DIR = ${platform_dir}\r
f51461c8
LG
1233PLATFORM_OUTPUT_DIR = ${platform_output_directory}\r
1234\r
1235#\r
1236# Module Macro Definition\r
1237#\r
1238MODULE_NAME = ${module_name}\r
1239MODULE_GUID = ${module_guid}\r
867d1cd4 1240MODULE_NAME_GUID = ${module_name_guid}\r
f51461c8
LG
1241MODULE_VERSION = ${module_version}\r
1242MODULE_TYPE = ${module_type}\r
1243MODULE_FILE = ${module_file}\r
1244MODULE_FILE_BASE_NAME = ${module_file_base_name}\r
1245BASE_NAME = $(MODULE_NAME)\r
1246MODULE_RELATIVE_DIR = ${module_relative_directory}\r
01e418d6 1247MODULE_DIR = ${module_dir}\r
f51461c8
LG
1248\r
1249#\r
1250# Build Configuration Macro Definition\r
1251#\r
1252ARCH = ${architecture}\r
1253TOOLCHAIN = ${toolchain_tag}\r
1254TOOLCHAIN_TAG = ${toolchain_tag}\r
1255TARGET = ${build_target}\r
1256\r
1257#\r
1258# Build Directory Macro Definition\r
1259#\r
1260# PLATFORM_BUILD_DIR = ${platform_build_directory}\r
1261BUILD_DIR = ${platform_build_directory}\r
1262BIN_DIR = $(BUILD_DIR)${separator}${architecture}\r
1263LIB_DIR = $(BIN_DIR)\r
1264MODULE_BUILD_DIR = ${module_build_directory}\r
1265OUTPUT_DIR = ${module_output_directory}\r
1266DEBUG_DIR = ${module_debug_directory}\r
1267DEST_DIR_OUTPUT = $(OUTPUT_DIR)\r
1268DEST_DIR_DEBUG = $(DEBUG_DIR)\r
1269\r
1270#\r
1271# Tools definitions specific to this module\r
1272#\r
1273${BEGIN}${module_tool_definitions}\r
1274${END}\r
1275MAKE_FILE = ${makefile_path}\r
1276\r
1277#\r
1278# Shell Command Macro\r
1279#\r
1280${BEGIN}${shell_command_code} = ${shell_command}\r
1281${END}\r
1282\r
1283${custom_makefile_content}\r
1284\r
1285#\r
1286# Target used when called from platform makefile, which will bypass the build of dependent libraries\r
1287#\r
1288\r
1289pbuild: init all\r
1290\r
1291\r
1292#\r
1293# ModuleTarget\r
1294#\r
1295\r
1296mbuild: init all\r
1297\r
1298#\r
1299# Build Target used in multi-thread build mode, which no init target is needed\r
1300#\r
1301\r
1302tbuild: all\r
1303\r
1304#\r
1305# Initialization target: print build information and create necessary directories\r
1306#\r
1307init:\r
1308\t-@echo Building ... $(MODULE_DIR)${separator}$(MODULE_FILE) [$(ARCH)]\r
1309${BEGIN}\t-@${create_directory_command}\n${END}\\r
1310\r
1311''')\r
1312\r
1313 ## Constructor of CustomMakefile\r
1314 #\r
1315 # @param ModuleAutoGen Object of ModuleAutoGen class\r
1316 #\r
1317 def __init__(self, ModuleAutoGen):\r
1318 BuildFile.__init__(self, ModuleAutoGen)\r
1319 self.PlatformInfo = self._AutoGenObject.PlatformInfo\r
1320 self.IntermediateDirectoryList = ["$(DEBUG_DIR)", "$(OUTPUT_DIR)"]\r
1321\r
1322 # Compose a dict object containing information used to do replacement in template\r
4c92c81d
CJ
1323 @property\r
1324 def _TemplateDict(self):\r
f51461c8 1325 Separator = self._SEP_[self._FileType]\r
7c12d613
JC
1326 MyAgo = self._AutoGenObject\r
1327 if self._FileType not in MyAgo.CustomMakefile:\r
f51461c8 1328 EdkLogger.error('build', OPTION_NOT_SUPPORTED, "No custom makefile for %s" % self._FileType,\r
7c12d613 1329 ExtraData="[%s]" % str(MyAgo))\r
01e418d6 1330 MakefilePath = mws.join(\r
7c12d613
JC
1331 MyAgo.WorkspaceDir,\r
1332 MyAgo.CustomMakefile[self._FileType]\r
f51461c8
LG
1333 )\r
1334 try:\r
1335 CustomMakefile = open(MakefilePath, 'r').read()\r
1336 except:\r
7c12d613
JC
1337 EdkLogger.error('build', FILE_OPEN_FAILURE, File=str(MyAgo),\r
1338 ExtraData=MyAgo.CustomMakefile[self._FileType])\r
f51461c8
LG
1339\r
1340 # tools definitions\r
1341 ToolsDef = []\r
7c12d613 1342 for Tool in MyAgo.BuildOption:\r
f51461c8
LG
1343 # Don't generate MAKE_FLAGS in makefile. It's put in environment variable.\r
1344 if Tool == "MAKE":\r
1345 continue\r
7c12d613 1346 for Attr in MyAgo.BuildOption[Tool]:\r
f51461c8
LG
1347 if Attr == "FAMILY":\r
1348 continue\r
1349 elif Attr == "PATH":\r
7c12d613 1350 ToolsDef.append("%s = %s" % (Tool, MyAgo.BuildOption[Tool][Attr]))\r
f51461c8 1351 else:\r
7c12d613 1352 ToolsDef.append("%s_%s = %s" % (Tool, Attr, MyAgo.BuildOption[Tool][Attr]))\r
f51461c8
LG
1353 ToolsDef.append("")\r
1354\r
1355 MakefileName = self._FILE_NAME_[self._FileType]\r
1356 MakefileTemplateDict = {\r
1357 "makefile_header" : self._FILE_HEADER_[self._FileType],\r
1358 "makefile_path" : os.path.join("$(MODULE_BUILD_DIR)", MakefileName),\r
1359 "platform_name" : self.PlatformInfo.Name,\r
1360 "platform_guid" : self.PlatformInfo.Guid,\r
1361 "platform_version" : self.PlatformInfo.Version,\r
1362 "platform_relative_directory": self.PlatformInfo.SourceDir,\r
1363 "platform_output_directory" : self.PlatformInfo.OutputDir,\r
7c12d613
JC
1364 "platform_dir" : MyAgo.Macros["PLATFORM_DIR"],\r
1365\r
1366 "module_name" : MyAgo.Name,\r
1367 "module_guid" : MyAgo.Guid,\r
1368 "module_name_guid" : MyAgo.UniqueBaseName,\r
1369 "module_version" : MyAgo.Version,\r
1370 "module_type" : MyAgo.ModuleType,\r
1371 "module_file" : MyAgo.MetaFile,\r
1372 "module_file_base_name" : MyAgo.MetaFile.BaseName,\r
1373 "module_relative_directory" : MyAgo.SourceDir,\r
1374 "module_dir" : mws.join (MyAgo.WorkspaceDir, MyAgo.SourceDir),\r
1375\r
1376 "architecture" : MyAgo.Arch,\r
1377 "toolchain_tag" : MyAgo.ToolChain,\r
1378 "build_target" : MyAgo.BuildTarget,\r
f51461c8
LG
1379\r
1380 "platform_build_directory" : self.PlatformInfo.BuildDir,\r
7c12d613
JC
1381 "module_build_directory" : MyAgo.BuildDir,\r
1382 "module_output_directory" : MyAgo.OutputDir,\r
1383 "module_debug_directory" : MyAgo.DebugDir,\r
f51461c8
LG
1384\r
1385 "separator" : Separator,\r
1386 "module_tool_definitions" : ToolsDef,\r
1387\r
f8d11e5a
FB
1388 "shell_command_code" : list(self._SHELL_CMD_[self._FileType].keys()),\r
1389 "shell_command" : list(self._SHELL_CMD_[self._FileType].values()),\r
f51461c8
LG
1390\r
1391 "create_directory_command" : self.GetCreateDirectoryCommand(self.IntermediateDirectoryList),\r
1392 "custom_makefile_content" : CustomMakefile\r
1393 }\r
1394\r
1395 return MakefileTemplateDict\r
1396\r
f51461c8
LG
1397## PlatformMakefile class\r
1398#\r
1399# This class encapsules makefie and its generation for platform. It uses\r
1400# template to generate the content of makefile. The content of makefile will be\r
1401# got from PlatformAutoGen object.\r
1402#\r
1403class PlatformMakefile(BuildFile):\r
1404 ## template used to generate the makefile for platform\r
1405 _TEMPLATE_ = TemplateString('''\\r
1406${makefile_header}\r
1407\r
1408#\r
1409# Platform Macro Definition\r
1410#\r
1411PLATFORM_NAME = ${platform_name}\r
1412PLATFORM_GUID = ${platform_guid}\r
1413PLATFORM_VERSION = ${platform_version}\r
1414PLATFORM_FILE = ${platform_file}\r
7a5f1426 1415PLATFORM_DIR = ${platform_dir}\r
f51461c8
LG
1416PLATFORM_OUTPUT_DIR = ${platform_output_directory}\r
1417\r
1418#\r
1419# Build Configuration Macro Definition\r
1420#\r
1421TOOLCHAIN = ${toolchain_tag}\r
1422TOOLCHAIN_TAG = ${toolchain_tag}\r
1423TARGET = ${build_target}\r
1424\r
1425#\r
1426# Build Directory Macro Definition\r
1427#\r
1428BUILD_DIR = ${platform_build_directory}\r
1429FV_DIR = ${platform_build_directory}${separator}FV\r
1430\r
1431#\r
1432# Shell Command Macro\r
1433#\r
1434${BEGIN}${shell_command_code} = ${shell_command}\r
1435${END}\r
1436\r
1437MAKE = ${make_path}\r
1438MAKE_FILE = ${makefile_path}\r
1439\r
1440#\r
1441# Default target\r
1442#\r
1443all: init build_libraries build_modules\r
1444\r
1445#\r
1446# Initialization target: print build information and create necessary directories\r
1447#\r
1448init:\r
1449\t-@echo Building ... $(PLATFORM_FILE) [${build_architecture_list}]\r
1450\t${BEGIN}-@${create_directory_command}\r
1451\t${END}\r
1452#\r
1453# library build target\r
1454#\r
1455libraries: init build_libraries\r
1456\r
1457#\r
1458# module build target\r
1459#\r
1460modules: init build_libraries build_modules\r
1461\r
1462#\r
1463# Build all libraries:\r
1464#\r
1465build_libraries:\r
1466${BEGIN}\t@"$(MAKE)" $(MAKE_FLAGS) -f ${library_makefile_list} pbuild\r
1467${END}\t@cd $(BUILD_DIR)\r
1468\r
1469#\r
1470# Build all modules:\r
1471#\r
1472build_modules:\r
1473${BEGIN}\t@"$(MAKE)" $(MAKE_FLAGS) -f ${module_makefile_list} pbuild\r
1474${END}\t@cd $(BUILD_DIR)\r
1475\r
1476#\r
1477# Clean intermediate files\r
1478#\r
1479clean:\r
1480\t${BEGIN}-@${library_build_command} clean\r
1481\t${END}${BEGIN}-@${module_build_command} clean\r
1482\t${END}@cd $(BUILD_DIR)\r
1483\r
1484#\r
1485# Clean all generated files except to makefile\r
1486#\r
1487cleanall:\r
1488${BEGIN}\t${cleanall_command}\r
1489${END}\r
1490\r
1491#\r
1492# Clean all library files\r
1493#\r
1494cleanlib:\r
1495\t${BEGIN}-@${library_build_command} cleanall\r
1496\t${END}@cd $(BUILD_DIR)\n\r
1497''')\r
1498\r
1499 ## Constructor of PlatformMakefile\r
1500 #\r
1501 # @param ModuleAutoGen Object of PlatformAutoGen class\r
1502 #\r
1503 def __init__(self, PlatformAutoGen):\r
1504 BuildFile.__init__(self, PlatformAutoGen)\r
1505 self.ModuleBuildCommandList = []\r
1506 self.ModuleMakefileList = []\r
1507 self.IntermediateDirectoryList = []\r
1508 self.ModuleBuildDirectoryList = []\r
1509 self.LibraryBuildDirectoryList = []\r
03af2753 1510 self.LibraryMakeCommandList = []\r
f51461c8
LG
1511\r
1512 # Compose a dict object containing information used to do replacement in template\r
4c92c81d
CJ
1513 @property\r
1514 def _TemplateDict(self):\r
f51461c8
LG
1515 Separator = self._SEP_[self._FileType]\r
1516\r
7c12d613
JC
1517 MyAgo = self._AutoGenObject\r
1518 if "MAKE" not in MyAgo.ToolDefinition or "PATH" not in MyAgo.ToolDefinition["MAKE"]:\r
f51461c8 1519 EdkLogger.error("build", OPTION_MISSING, "No MAKE command defined. Please check your tools_def.txt!",\r
7c12d613 1520 ExtraData="[%s]" % str(MyAgo))\r
f51461c8
LG
1521\r
1522 self.IntermediateDirectoryList = ["$(BUILD_DIR)"]\r
1523 self.ModuleBuildDirectoryList = self.GetModuleBuildDirectoryList()\r
1524 self.LibraryBuildDirectoryList = self.GetLibraryBuildDirectoryList()\r
1525\r
1526 MakefileName = self._FILE_NAME_[self._FileType]\r
1527 LibraryMakefileList = []\r
1528 LibraryMakeCommandList = []\r
1529 for D in self.LibraryBuildDirectoryList:\r
7c12d613 1530 D = self.PlaceMacro(D, {"BUILD_DIR":MyAgo.BuildDir})\r
f51461c8
LG
1531 Makefile = os.path.join(D, MakefileName)\r
1532 Command = self._MAKE_TEMPLATE_[self._FileType] % {"file":Makefile}\r
1533 LibraryMakefileList.append(Makefile)\r
1534 LibraryMakeCommandList.append(Command)\r
03af2753 1535 self.LibraryMakeCommandList = LibraryMakeCommandList\r
f51461c8
LG
1536\r
1537 ModuleMakefileList = []\r
1538 ModuleMakeCommandList = []\r
1539 for D in self.ModuleBuildDirectoryList:\r
7c12d613 1540 D = self.PlaceMacro(D, {"BUILD_DIR":MyAgo.BuildDir})\r
f51461c8
LG
1541 Makefile = os.path.join(D, MakefileName)\r
1542 Command = self._MAKE_TEMPLATE_[self._FileType] % {"file":Makefile}\r
1543 ModuleMakefileList.append(Makefile)\r
1544 ModuleMakeCommandList.append(Command)\r
1545\r
1546 MakefileTemplateDict = {\r
1547 "makefile_header" : self._FILE_HEADER_[self._FileType],\r
1548 "makefile_path" : os.path.join("$(BUILD_DIR)", MakefileName),\r
7c12d613 1549 "make_path" : MyAgo.ToolDefinition["MAKE"]["PATH"],\r
f51461c8 1550 "makefile_name" : MakefileName,\r
7c12d613
JC
1551 "platform_name" : MyAgo.Name,\r
1552 "platform_guid" : MyAgo.Guid,\r
1553 "platform_version" : MyAgo.Version,\r
1554 "platform_file" : MyAgo.MetaFile,\r
1555 "platform_relative_directory": MyAgo.SourceDir,\r
1556 "platform_output_directory" : MyAgo.OutputDir,\r
1557 "platform_build_directory" : MyAgo.BuildDir,\r
1558 "platform_dir" : MyAgo.Macros["PLATFORM_DIR"],\r
1559\r
1560 "toolchain_tag" : MyAgo.ToolChain,\r
1561 "build_target" : MyAgo.BuildTarget,\r
f8d11e5a
FB
1562 "shell_command_code" : list(self._SHELL_CMD_[self._FileType].keys()),\r
1563 "shell_command" : list(self._SHELL_CMD_[self._FileType].values()),\r
7c12d613
JC
1564 "build_architecture_list" : MyAgo.Arch,\r
1565 "architecture" : MyAgo.Arch,\r
f51461c8
LG
1566 "separator" : Separator,\r
1567 "create_directory_command" : self.GetCreateDirectoryCommand(self.IntermediateDirectoryList),\r
1568 "cleanall_command" : self.GetRemoveDirectoryCommand(self.IntermediateDirectoryList),\r
1569 "library_makefile_list" : LibraryMakefileList,\r
1570 "module_makefile_list" : ModuleMakefileList,\r
1571 "library_build_command" : LibraryMakeCommandList,\r
1572 "module_build_command" : ModuleMakeCommandList,\r
1573 }\r
1574\r
1575 return MakefileTemplateDict\r
1576\r
1577 ## Get the root directory list for intermediate files of all modules build\r
1578 #\r
1579 # @retval list The list of directory\r
1580 #\r
1581 def GetModuleBuildDirectoryList(self):\r
1582 DirList = []\r
1583 for ModuleAutoGen in self._AutoGenObject.ModuleAutoGenList:\r
97fa0ee9
YL
1584 if not ModuleAutoGen.IsBinaryModule:\r
1585 DirList.append(os.path.join(self._AutoGenObject.BuildDir, ModuleAutoGen.BuildDir))\r
f51461c8
LG
1586 return DirList\r
1587\r
1588 ## Get the root directory list for intermediate files of all libraries build\r
1589 #\r
1590 # @retval list The list of directory\r
1591 #\r
1592 def GetLibraryBuildDirectoryList(self):\r
1593 DirList = []\r
1594 for LibraryAutoGen in self._AutoGenObject.LibraryAutoGenList:\r
db4d47fd 1595 if not LibraryAutoGen.IsBinaryModule and not LibraryAutoGen.CanSkipbyHash():\r
97fa0ee9 1596 DirList.append(os.path.join(self._AutoGenObject.BuildDir, LibraryAutoGen.BuildDir))\r
f51461c8
LG
1597 return DirList\r
1598\r
f51461c8
LG
1599## TopLevelMakefile class\r
1600#\r
1601# This class encapsules makefie and its generation for entrance makefile. It\r
1602# uses template to generate the content of makefile. The content of makefile\r
1603# will be got from WorkspaceAutoGen object.\r
1604#\r
1605class TopLevelMakefile(BuildFile):\r
1606 ## template used to generate toplevel makefile\r
97fa0ee9 1607 _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}''')\r
f51461c8
LG
1608\r
1609 ## Constructor of TopLevelMakefile\r
1610 #\r
1611 # @param Workspace Object of WorkspaceAutoGen class\r
1612 #\r
1613 def __init__(self, Workspace):\r
1614 BuildFile.__init__(self, Workspace)\r
1615 self.IntermediateDirectoryList = []\r
1616\r
1617 # Compose a dict object containing information used to do replacement in template\r
4c92c81d
CJ
1618 @property\r
1619 def _TemplateDict(self):\r
f51461c8
LG
1620 Separator = self._SEP_[self._FileType]\r
1621\r
1622 # any platform autogen object is ok because we just need common information\r
7c12d613 1623 MyAgo = self._AutoGenObject\r
f51461c8 1624\r
7c12d613 1625 if "MAKE" not in MyAgo.ToolDefinition or "PATH" not in MyAgo.ToolDefinition["MAKE"]:\r
f51461c8 1626 EdkLogger.error("build", OPTION_MISSING, "No MAKE command defined. Please check your tools_def.txt!",\r
7c12d613 1627 ExtraData="[%s]" % str(MyAgo))\r
f51461c8 1628\r
7c12d613 1629 for Arch in MyAgo.ArchList:\r
f51461c8
LG
1630 self.IntermediateDirectoryList.append(Separator.join(["$(BUILD_DIR)", Arch]))\r
1631 self.IntermediateDirectoryList.append("$(FV_DIR)")\r
1632\r
1633 # TRICK: for not generating GenFds call in makefile if no FDF file\r
1634 MacroList = []\r
7c12d613
JC
1635 if MyAgo.FdfFile is not None and MyAgo.FdfFile != "":\r
1636 FdfFileList = [MyAgo.FdfFile]\r
f51461c8 1637 # macros passed to GenFds\r
f51461c8
LG
1638 MacroDict = {}\r
1639 MacroDict.update(GlobalData.gGlobalDefines)\r
1640 MacroDict.update(GlobalData.gCommandLineDefines)\r
f51461c8
LG
1641 for MacroName in MacroDict:\r
1642 if MacroDict[MacroName] != "":\r
1643 MacroList.append('"%s=%s"' % (MacroName, MacroDict[MacroName].replace('\\', '\\\\')))\r
1644 else:\r
1645 MacroList.append('"%s"' % MacroName)\r
1646 else:\r
1647 FdfFileList = []\r
1648\r
1649 # pass extra common options to external program called in makefile, currently GenFds.exe\r
1650 ExtraOption = ''\r
1651 LogLevel = EdkLogger.GetLevel()\r
1652 if LogLevel == EdkLogger.VERBOSE:\r
1653 ExtraOption += " -v"\r
1654 elif LogLevel <= EdkLogger.DEBUG_9:\r
1655 ExtraOption += " -d %d" % (LogLevel - 1)\r
1656 elif LogLevel == EdkLogger.QUIET:\r
1657 ExtraOption += " -q"\r
1658\r
1659 if GlobalData.gCaseInsensitive:\r
1660 ExtraOption += " -c"\r
37de70b7
YZ
1661 if GlobalData.gEnableGenfdsMultiThread:\r
1662 ExtraOption += " --genfds-multi-thread"\r
97fa0ee9
YL
1663 if GlobalData.gIgnoreSource:\r
1664 ExtraOption += " --ignore-sources"\r
1665\r
0f228f19
B
1666 for pcd in GlobalData.BuildOptionPcd:\r
1667 if pcd[2]:\r
1668 pcdname = '.'.join(pcd[0:3])\r
1669 else:\r
1670 pcdname = '.'.join(pcd[0:2])\r
1671 if pcd[3].startswith('{'):\r
1672 ExtraOption += " --pcd " + pcdname + '=' + 'H' + '"' + pcd[3] + '"'\r
1673 else:\r
1674 ExtraOption += " --pcd " + pcdname + '=' + pcd[3]\r
6b17c11b 1675\r
f51461c8
LG
1676 MakefileName = self._FILE_NAME_[self._FileType]\r
1677 SubBuildCommandList = []\r
7c12d613 1678 for A in MyAgo.ArchList:\r
f51461c8
LG
1679 Command = self._MAKE_TEMPLATE_[self._FileType] % {"file":os.path.join("$(BUILD_DIR)", A, MakefileName)}\r
1680 SubBuildCommandList.append(Command)\r
1681\r
1682 MakefileTemplateDict = {\r
1683 "makefile_header" : self._FILE_HEADER_[self._FileType],\r
1684 "makefile_path" : os.path.join("$(BUILD_DIR)", MakefileName),\r
7c12d613
JC
1685 "make_path" : MyAgo.ToolDefinition["MAKE"]["PATH"],\r
1686 "platform_name" : MyAgo.Name,\r
1687 "platform_guid" : MyAgo.Guid,\r
1688 "platform_version" : MyAgo.Version,\r
1689 "platform_build_directory" : MyAgo.BuildDir,\r
97fa0ee9 1690 "conf_directory" : GlobalData.gConfDirectory,\r
f51461c8 1691\r
7c12d613
JC
1692 "toolchain_tag" : MyAgo.ToolChain,\r
1693 "build_target" : MyAgo.BuildTarget,\r
f8d11e5a
FB
1694 "shell_command_code" : list(self._SHELL_CMD_[self._FileType].keys()),\r
1695 "shell_command" : list(self._SHELL_CMD_[self._FileType].values()),\r
7c12d613
JC
1696 'arch' : list(MyAgo.ArchList),\r
1697 "build_architecture_list" : ','.join(MyAgo.ArchList),\r
f51461c8
LG
1698 "separator" : Separator,\r
1699 "create_directory_command" : self.GetCreateDirectoryCommand(self.IntermediateDirectoryList),\r
1700 "cleanall_command" : self.GetRemoveDirectoryCommand(self.IntermediateDirectoryList),\r
1701 "sub_build_command" : SubBuildCommandList,\r
1702 "fdf_file" : FdfFileList,\r
7c12d613
JC
1703 "active_platform" : str(MyAgo),\r
1704 "fd" : MyAgo.FdTargetList,\r
1705 "fv" : MyAgo.FvTargetList,\r
1706 "cap" : MyAgo.CapTargetList,\r
f51461c8
LG
1707 "extra_options" : ExtraOption,\r
1708 "macro" : MacroList,\r
1709 }\r
1710\r
1711 return MakefileTemplateDict\r
1712\r
1713 ## Get the root directory list for intermediate files of all modules build\r
1714 #\r
1715 # @retval list The list of directory\r
1716 #\r
1717 def GetModuleBuildDirectoryList(self):\r
1718 DirList = []\r
1719 for ModuleAutoGen in self._AutoGenObject.ModuleAutoGenList:\r
97fa0ee9
YL
1720 if not ModuleAutoGen.IsBinaryModule:\r
1721 DirList.append(os.path.join(self._AutoGenObject.BuildDir, ModuleAutoGen.BuildDir))\r
f51461c8
LG
1722 return DirList\r
1723\r
1724 ## Get the root directory list for intermediate files of all libraries build\r
1725 #\r
1726 # @retval list The list of directory\r
1727 #\r
1728 def GetLibraryBuildDirectoryList(self):\r
1729 DirList = []\r
1730 for LibraryAutoGen in self._AutoGenObject.LibraryAutoGenList:\r
db4d47fd 1731 if not LibraryAutoGen.IsBinaryModule and not LibraryAutoGen.CanSkipbyHash():\r
97fa0ee9 1732 DirList.append(os.path.join(self._AutoGenObject.BuildDir, LibraryAutoGen.BuildDir))\r
f51461c8
LG
1733 return DirList\r
1734\r
f51461c8
LG
1735# This acts like the main() function for the script, unless it is 'import'ed into another script.\r
1736if __name__ == '__main__':\r
1737 pass\r
1738\r