2 # The engine for building files
4 # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>
5 # SPDX-License-Identifier: BSD-2-Clause-Patent
11 from __future__
import print_function
12 import Common
.LongFilePathOs
as os
16 from Common
.LongFilePathSupport
import OpenLongFilePath
as open
18 from Common
.GlobalData
import *
19 from Common
.BuildToolError
import *
20 from Common
.Misc
import tdict
, PathClass
21 from Common
.StringUtils
import NormPath
22 from Common
.DataType
import *
24 import Common
.EdkLogger
as EdkLogger
26 ## Convert file type to file list macro name
28 # @param FileType The name of file type
30 # @retval string The name of macro
32 def FileListMacro(FileType
):
33 return "%sS" % FileType
.replace("-", "_").upper()
35 ## Convert file type to list file macro name
37 # @param FileType The name of file type
39 # @retval string The name of macro
41 def ListFileMacro(FileType
):
42 return "%s_LIST" % FileListMacro(FileType
)
44 class TargetDescBlock(object):
45 def __init__(self
, Inputs
, Outputs
, Commands
, Dependencies
):
46 self
.InitWorker(Inputs
, Outputs
, Commands
, Dependencies
)
48 def InitWorker(self
, Inputs
, Outputs
, Commands
, Dependencies
):
50 self
.Outputs
= Outputs
51 self
.Commands
= Commands
52 self
.Dependencies
= Dependencies
54 self
.Target
= self
.Outputs
[0]
59 return self
.Target
.Path
62 return hash(self
.Target
.Path
)
64 def __eq__(self
, Other
):
65 if isinstance(Other
, type(self
)):
66 return Other
.Target
.Path
== self
.Target
.Path
68 return str(Other
) == self
.Target
.Path
70 def AddInput(self
, Input
):
71 if Input
not in self
.Inputs
:
72 self
.Inputs
.append(Input
)
74 def IsMultipleInput(self
):
75 return len(self
.Inputs
) > 1
77 ## Class for one build rule
79 # This represents a build rule which can give out corresponding command list for
80 # building the given source file(s). The result can be used for generating the
81 # target for makefile.
84 INC_LIST_MACRO
= "INC_LIST"
89 # @param Input The dictionary representing input file(s) for a rule
90 # @param Output The list representing output file(s) for a rule
91 # @param Command The list containing commands to generate the output from input
93 def __init__(self
, Type
, Input
, Output
, Command
, ExtraDependency
=None):
94 # The Input should not be empty
102 self
.FileListMacro
= FileListMacro(Type
)
103 self
.ListFileMacro
= ListFileMacro(Type
)
104 self
.IncListFileMacro
= self
.INC_LIST_MACRO
106 self
.SourceFileType
= Type
107 # source files listed not in TAB_STAR or "?" pattern format
108 if not ExtraDependency
:
109 self
.ExtraSourceFileList
= []
111 self
.ExtraSourceFileList
= ExtraDependency
114 # Search macros used in command lines for <FILE_TYPE>_LIST and INC_LIST.
115 # If found, generate a file to keep the input files used to get over the
116 # limitation of command line length
119 self
.CommandList
= []
120 for CmdLine
in Command
:
121 self
.MacroList
.extend(gMacroRefPattern
.findall(CmdLine
))
122 # replace path separator with native one
123 self
.CommandList
.append(CmdLine
)
125 # Indicate what should be generated
126 if self
.FileListMacro
in self
.MacroList
:
127 self
.GenFileListMacro
= True
129 self
.GenFileListMacro
= False
131 if self
.ListFileMacro
in self
.MacroList
:
132 self
.GenListFile
= True
133 self
.GenFileListMacro
= True
135 self
.GenListFile
= False
137 if self
.INC_LIST_MACRO
in self
.MacroList
:
138 self
.GenIncListFile
= True
140 self
.GenIncListFile
= False
143 self
.IsMultipleInput
= False
144 self
.SourceFileExtList
= set()
146 Base
, Ext
= os
.path
.splitext(File
)
147 if Base
.find(TAB_STAR
) >= 0:
148 # There's TAB_STAR in the file name
149 self
.IsMultipleInput
= True
150 self
.GenFileListMacro
= True
151 elif Base
.find("?") < 0:
152 # There's no TAB_STAR and "?" in file name
153 self
.ExtraSourceFileList
.append(File
)
155 self
.SourceFileExtList
.add(Ext
)
158 self
.DestFileList
= []
160 self
.DestFileList
.append(File
)
162 # All build targets generated by this rule for a module
163 self
.BuildTargets
= {}
165 ## str() function support
171 SourceString
+= " %s %s %s" % (self
.SourceFileType
, " ".join(self
.SourceFileExtList
), self
.ExtraSourceFileList
)
172 DestString
= ", ".join(self
.DestFileList
)
173 CommandString
= "\n\t".join(self
.CommandList
)
174 return "%s : %s\n\t%s" % (DestString
, SourceString
, CommandString
)
176 def Instantiate(self
, Macros
={}):
177 NewRuleObject
= copy
.copy(self
)
178 NewRuleObject
.BuildTargets
= {}
179 NewRuleObject
.DestFileList
= []
180 for File
in self
.DestFileList
:
181 NewRuleObject
.DestFileList
.append(PathClass(NormPath(File
, Macros
)))
184 ## Apply the rule to given source file(s)
186 # @param SourceFile One file or a list of files to be built
187 # @param RelativeToDir The relative path of the source file
188 # @param PathSeparator Path separator
190 # @retval tuple (Source file in full path, List of individual sourcefiles, Destination file, List of build commands)
192 def Apply(self
, SourceFile
, BuildRuleOrder
=None):
193 if not self
.CommandList
or not self
.DestFileList
:
197 if self
.IsMultipleInput
:
203 # SourceFile must be a list
204 SrcFile
= "$(%s)" % self
.FileListMacro
206 SrcFileName
, SrcFileBase
, SrcFileExt
= SourceFile
.Name
, SourceFile
.BaseName
, SourceFile
.Ext
208 SrcFileDir
= SourceFile
.SubDir
213 SrcFile
= SourceFile
.Path
214 SrcPath
= SourceFile
.Dir
216 # destination file (the first one)
217 if self
.DestFileList
:
218 DestFile
= self
.DestFileList
[0].Path
219 DestPath
= self
.DestFileList
[0].Dir
220 DestFileName
= self
.DestFileList
[0].Name
221 DestFileBase
, DestFileExt
= self
.DestFileList
[0].BaseName
, self
.DestFileList
[0].Ext
229 BuildRulePlaceholderDict
= {
233 "s_dir" : SrcFileDir
,
234 "s_name" : SrcFileName
,
235 "s_base" : SrcFileBase
,
236 "s_ext" : SrcFileExt
,
240 "d_name" : DestFileName
,
241 "d_base" : DestFileBase
,
242 "d_ext" : DestFileExt
,
246 for File
in self
.DestFileList
:
247 File
= string
.Template(str(File
)).safe_substitute(BuildRulePlaceholderDict
)
248 File
= string
.Template(str(File
)).safe_substitute(BuildRulePlaceholderDict
)
249 DstFile
.append(PathClass(File
, IsBinary
=True))
251 if DstFile
[0] in self
.BuildTargets
:
252 TargetDesc
= self
.BuildTargets
[DstFile
[0]]
253 if BuildRuleOrder
and SourceFile
.Ext
in BuildRuleOrder
:
254 Index
= BuildRuleOrder
.index(SourceFile
.Ext
)
255 for Input
in TargetDesc
.Inputs
:
256 if Input
.Ext
not in BuildRuleOrder
or BuildRuleOrder
.index(Input
.Ext
) > Index
:
258 # Command line should be regenerated since some macros are different
260 CommandList
= self
._BuildCommand
(BuildRulePlaceholderDict
)
261 TargetDesc
.InitWorker([SourceFile
], DstFile
, CommandList
, self
.ExtraSourceFileList
)
264 TargetDesc
.AddInput(SourceFile
)
266 CommandList
= self
._BuildCommand
(BuildRulePlaceholderDict
)
267 TargetDesc
= TargetDescBlock([SourceFile
], DstFile
, CommandList
, self
.ExtraSourceFileList
)
268 TargetDesc
.ListFileMacro
= self
.ListFileMacro
269 TargetDesc
.FileListMacro
= self
.FileListMacro
270 TargetDesc
.IncListFileMacro
= self
.IncListFileMacro
271 TargetDesc
.GenFileListMacro
= self
.GenFileListMacro
272 TargetDesc
.GenListFile
= self
.GenListFile
273 TargetDesc
.GenIncListFile
= self
.GenIncListFile
274 self
.BuildTargets
[DstFile
[0]] = TargetDesc
277 def _BuildCommand(self
, Macros
):
279 for CommandString
in self
.CommandList
:
280 CommandString
= string
.Template(CommandString
).safe_substitute(Macros
)
281 CommandString
= string
.Template(CommandString
).safe_substitute(Macros
)
282 CommandList
.append(CommandString
)
285 ## Class for build rules
287 # BuildRule class parses rules defined in a file or passed by caller, and converts
288 # the rule into FileBuildRule object.
291 _SectionHeader
= "SECTIONHEADER"
293 _SubSectionHeader
= "SUBSECTIONHEADER"
294 _SubSection
= "SUBSECTION"
295 _InputFile
= "INPUTFILE"
296 _OutputFile
= "OUTPUTFILE"
297 _ExtraDependency
= "EXTRADEPENDENCY"
299 _UnknownSection
= "UNKNOWNSECTION"
301 _SubSectionList
= [_InputFile
, _OutputFile
, _Command
]
304 _FileTypePattern
= re
.compile("^[_a-zA-Z][_\-0-9a-zA-Z]*$")
305 _BinaryFileRule
= FileBuildRule(TAB_DEFAULT_BINARY_FILE
, [], [os
.path
.join("$(OUTPUT_DIR)", "${s_name}")],
306 ["$(CP) ${src} ${dst}"], [])
310 # @param File The file containing build rules in a well defined format
311 # @param Content The string list of build rules in a well defined format
312 # @param LineIndex The line number from which the parsing will begin
313 # @param SupportedFamily The list of supported tool chain families
315 def __init__(self
, File
=None, Content
=None, LineIndex
=0, SupportedFamily
=[TAB_COMPILER_MSFT
, "INTEL", "GCC", "RVCT"]):
317 # Read build rules from file if it's not none
320 self
.RuleContent
= open(File
, 'r').readlines()
322 EdkLogger
.error("build", FILE_OPEN_FAILURE
, ExtraData
=File
)
323 elif Content
is not None:
324 self
.RuleContent
= Content
326 EdkLogger
.error("build", PARAMETER_MISSING
, ExtraData
="No rule file or string given")
328 self
.SupportedToolChainFamilyList
= SupportedFamily
329 self
.RuleDatabase
= tdict(True, 4) # {FileExt, ModuleType, Arch, Family : FileBuildRule object}
330 self
.Ext2FileType
= {} # {ext : file-type}
331 self
.FileTypeList
= set()
333 self
._LineIndex
= LineIndex
335 self
._RuleInfo
= tdict(True, 2) # {toolchain family : {"InputFile": {}, "OutputFile" : [], "Command" : []}}
337 self
._BuildTypeList
= set()
338 self
._ArchList
= set()
339 self
._FamilyList
= []
340 self
._TotalToolChainFamilySet
= set()
341 self
._RuleObjectList
= [] # FileBuildRule object list
342 self
._FileVersion
= ""
346 # some intrinsic rules
347 self
.RuleDatabase
[TAB_DEFAULT_BINARY_FILE
, TAB_COMMON
, TAB_COMMON
, TAB_COMMON
] = self
._BinaryFileRule
348 self
.FileTypeList
.add(TAB_DEFAULT_BINARY_FILE
)
350 ## Parse the build rule strings
352 self
._State
= self
._Section
353 for Index
in range(self
._LineIndex
, len(self
.RuleContent
)):
354 # Clean up the line and replace path separator with native one
355 Line
= self
.RuleContent
[Index
].strip().replace(self
._PATH
_SEP
, os
.path
.sep
)
356 self
.RuleContent
[Index
] = Line
358 # find the build_rule_version
359 if Line
and Line
[0] == "#" and Line
.find(TAB_BUILD_RULE_VERSION
) != -1:
360 if Line
.find("=") != -1 and Line
.find("=") < (len(Line
) - 1) and (Line
[(Line
.find("=") + 1):]).split():
361 self
._FileVersion
= (Line
[(Line
.find("=") + 1):]).split()[0]
362 # skip empty or comment line
363 if Line
== "" or Line
[0] == "#":
366 # find out section header, enclosed by []
367 if Line
[0] == '[' and Line
[-1] == ']':
368 # merge last section information into rule database
370 self
._State
= self
._SectionHeader
371 # find out sub-section header, enclosed by <>
372 elif Line
[0] == '<' and Line
[-1] == '>':
373 if self
._State
!= self
._UnknownSection
:
374 self
._State
= self
._SubSectionHeader
376 # call section handler to parse each (sub)section
377 self
._StateHandler
[self
._State
](self
, Index
)
378 # merge last section information into rule database
381 ## Parse definitions under a section
383 # @param LineIndex The line index of build rule text
385 def ParseSection(self
, LineIndex
):
388 ## Parse definitions under a subsection
390 # @param LineIndex The line index of build rule text
392 def ParseSubSection(self
, LineIndex
):
393 # currently nothing here
396 ## Placeholder for not supported sections
398 # @param LineIndex The line index of build rule text
400 def SkipSection(self
, LineIndex
):
403 ## Merge section information just got into rule database
404 def EndOfSection(self
):
405 Database
= self
.RuleDatabase
406 # if there's specific toolchain family, 'COMMON' doesn't make sense any more
407 if len(self
._TotalToolChainFamilySet
) > 1 and TAB_COMMON
in self
._TotalToolChainFamilySet
:
408 self
._TotalToolChainFamilySet
.remove(TAB_COMMON
)
409 for Family
in self
._TotalToolChainFamilySet
:
410 Input
= self
._RuleInfo
[Family
, self
._InputFile
]
411 Output
= self
._RuleInfo
[Family
, self
._OutputFile
]
412 Command
= self
._RuleInfo
[Family
, self
._Command
]
413 ExtraDependency
= self
._RuleInfo
[Family
, self
._ExtraDependency
]
415 BuildRule
= FileBuildRule(self
._FileType
, Input
, Output
, Command
, ExtraDependency
)
416 for BuildType
in self
._BuildTypeList
:
417 for Arch
in self
._ArchList
:
418 Database
[self
._FileType
, BuildType
, Arch
, Family
] = BuildRule
419 for FileExt
in BuildRule
.SourceFileExtList
:
420 self
.Ext2FileType
[FileExt
] = self
._FileType
422 ## Parse section header
424 # @param LineIndex The line index of build rule text
426 def ParseSectionHeader(self
, LineIndex
):
427 self
._RuleInfo
= tdict(True, 2)
428 self
._BuildTypeList
= set()
429 self
._ArchList
= set()
430 self
._FamilyList
= []
431 self
._TotalToolChainFamilySet
= set()
433 RuleNameList
= self
.RuleContent
[LineIndex
][1:-1].split(',')
434 for RuleName
in RuleNameList
:
436 BuildType
= TAB_COMMON
437 TokenList
= [Token
.strip().upper() for Token
in RuleName
.split('.')]
438 # old format: Build.File-Type
439 if TokenList
[0] == "BUILD":
440 if len(TokenList
) == 1:
441 EdkLogger
.error("build", FORMAT_INVALID
, "Invalid rule section",
442 File
=self
.RuleFile
, Line
=LineIndex
+ 1,
443 ExtraData
=self
.RuleContent
[LineIndex
])
445 FileType
= TokenList
[1]
447 EdkLogger
.error("build", FORMAT_INVALID
, "No file type given",
448 File
=self
.RuleFile
, Line
=LineIndex
+ 1,
449 ExtraData
=self
.RuleContent
[LineIndex
])
450 if self
._FileTypePattern
.match(FileType
) is None:
451 EdkLogger
.error("build", FORMAT_INVALID
, File
=self
.RuleFile
, Line
=LineIndex
+ 1,
452 ExtraData
="Only character, number (non-first character), '_' and '-' are allowed in file type")
453 # new format: File-Type.Build-Type.Arch
456 FileType
= TokenList
[0]
457 elif FileType
!= TokenList
[0]:
458 EdkLogger
.error("build", FORMAT_INVALID
,
459 "Different file types are not allowed in the same rule section",
460 File
=self
.RuleFile
, Line
=LineIndex
+ 1,
461 ExtraData
=self
.RuleContent
[LineIndex
])
462 if len(TokenList
) > 1:
463 BuildType
= TokenList
[1]
464 if len(TokenList
) > 2:
466 self
._BuildTypeList
.add(BuildType
)
467 self
._ArchList
.add(Arch
)
469 if TAB_COMMON
in self
._BuildTypeList
and len(self
._BuildTypeList
) > 1:
470 EdkLogger
.error("build", FORMAT_INVALID
,
471 "Specific build types must not be mixed with common one",
472 File
=self
.RuleFile
, Line
=LineIndex
+ 1,
473 ExtraData
=self
.RuleContent
[LineIndex
])
474 if TAB_COMMON
in self
._ArchList
and len(self
._ArchList
) > 1:
475 EdkLogger
.error("build", FORMAT_INVALID
,
476 "Specific ARCH must not be mixed with common one",
477 File
=self
.RuleFile
, Line
=LineIndex
+ 1,
478 ExtraData
=self
.RuleContent
[LineIndex
])
480 self
._FileType
= FileType
481 self
._State
= self
._Section
482 self
.FileTypeList
.add(FileType
)
484 ## Parse sub-section header
486 # @param LineIndex The line index of build rule text
488 def ParseSubSectionHeader(self
, LineIndex
):
490 List
= self
.RuleContent
[LineIndex
][1:-1].split(',')
493 TokenList
= Section
.split('.')
494 Type
= TokenList
[0].strip().upper()
496 if SectionType
== "":
498 elif SectionType
!= Type
:
499 EdkLogger
.error("build", FORMAT_INVALID
,
500 "Two different section types are not allowed in the same sub-section",
501 File
=self
.RuleFile
, Line
=LineIndex
+ 1,
502 ExtraData
=self
.RuleContent
[LineIndex
])
504 if len(TokenList
) > 1:
505 Family
= TokenList
[1].strip().upper()
509 if Family
not in FamilyList
:
510 FamilyList
.append(Family
)
512 self
._FamilyList
= FamilyList
513 self
._TotalToolChainFamilySet
.update(FamilyList
)
514 self
._State
= SectionType
.upper()
515 if TAB_COMMON
in FamilyList
and len(FamilyList
) > 1:
516 EdkLogger
.error("build", FORMAT_INVALID
,
517 "Specific tool chain family should not be mixed with general one",
518 File
=self
.RuleFile
, Line
=LineIndex
+ 1,
519 ExtraData
=self
.RuleContent
[LineIndex
])
520 if self
._State
not in self
._StateHandler
:
521 EdkLogger
.error("build", FORMAT_INVALID
, File
=self
.RuleFile
, Line
=LineIndex
+ 1,
522 ExtraData
="Unknown subsection: %s" % self
.RuleContent
[LineIndex
])
523 ## Parse <InputFile> sub-section
525 # @param LineIndex The line index of build rule text
527 def ParseInputFileSubSection(self
, LineIndex
):
528 FileList
= [File
.strip() for File
in self
.RuleContent
[LineIndex
].split(",")]
529 for ToolChainFamily
in self
._FamilyList
:
530 if self
._RuleInfo
[ToolChainFamily
, self
._State
] is None:
531 self
._RuleInfo
[ToolChainFamily
, self
._State
] = []
532 self
._RuleInfo
[ToolChainFamily
, self
._State
].extend(FileList
)
534 ## Parse <ExtraDependency> sub-section
535 ## Parse <OutputFile> sub-section
536 ## Parse <Command> sub-section
538 # @param LineIndex The line index of build rule text
540 def ParseCommonSubSection(self
, LineIndex
):
541 for ToolChainFamily
in self
._FamilyList
:
542 if self
._RuleInfo
[ToolChainFamily
, self
._State
] is None:
543 self
._RuleInfo
[ToolChainFamily
, self
._State
] = []
544 self
._RuleInfo
[ToolChainFamily
, self
._State
].append(self
.RuleContent
[LineIndex
])
546 ## Get a build rule via [] operator
548 # @param FileExt The extension of a file
549 # @param ToolChainFamily The tool chain family name
550 # @param BuildVersion The build version number. TAB_STAR means any rule
553 # @retval FileType The file type string
554 # @retval FileBuildRule The object of FileBuildRule
556 # Key = (FileExt, ModuleType, Arch, ToolChainFamily)
557 def __getitem__(self
, Key
):
561 if Key
[0] in self
.Ext2FileType
:
562 Type
= self
.Ext2FileType
[Key
[0]]
563 elif Key
[0].upper() in self
.FileTypeList
:
564 Type
= Key
[0].upper()
569 Key
= (Type
,) + Key
[1:]
572 return self
.RuleDatabase
[Key
]
575 _SectionHeader
: ParseSectionHeader
,
576 _Section
: ParseSection
,
577 _SubSectionHeader
: ParseSubSectionHeader
,
578 _SubSection
: ParseSubSection
,
579 _InputFile
: ParseInputFileSubSection
,
580 _OutputFile
: ParseCommonSubSection
,
581 _ExtraDependency
: ParseCommonSubSection
,
582 _Command
: ParseCommonSubSection
,
583 _UnknownSection
: SkipSection
,
586 # This acts like the main() function for the script, unless it is 'import'ed into another
588 if __name__
== '__main__':
590 EdkLogger
.Initialize()
591 if len(sys
.argv
) > 1:
592 Br
= BuildRule(sys
.argv
[1])
593 print(str(Br
[".c", SUP_MODULE_DXE_DRIVER
, "IA32", TAB_COMPILER_MSFT
][1]))
595 print(str(Br
[".c", SUP_MODULE_DXE_DRIVER
, "IA32", "INTEL"][1]))
597 print(str(Br
[".c", SUP_MODULE_DXE_DRIVER
, "IA32", "GCC"][1]))
599 print(str(Br
[".ac", "ACPI_TABLE", "IA32", TAB_COMPILER_MSFT
][1]))
601 print(str(Br
[".h", "ACPI_TABLE", "IA32", "INTEL"][1]))
603 print(str(Br
[".ac", "ACPI_TABLE", "IA32", TAB_COMPILER_MSFT
][1]))
605 print(str(Br
[".s", SUP_MODULE_SEC
, "IPF", "COMMON"][1]))
607 print(str(Br
[".s", SUP_MODULE_SEC
][1]))