2 # The engine for building files
4 # Copyright (c) 2007 - 2014, 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.
17 import Common
.LongFilePathOs
as os
21 from Common
.LongFilePathSupport
import OpenLongFilePath
as open
23 from Common
.GlobalData
import *
24 from Common
.BuildToolError
import *
25 from Common
.Misc
import tdict
, PathClass
26 from Common
.String
import NormPath
27 from Common
.DataType
import *
29 import Common
.EdkLogger
as EdkLogger
31 ## Convert file type to file list macro name
33 # @param FileType The name of file type
35 # @retval string The name of macro
37 def FileListMacro(FileType
):
38 return "%sS" % FileType
.replace("-", "_").upper()
40 ## Convert file type to list file macro name
42 # @param FileType The name of file type
44 # @retval string The name of macro
46 def ListFileMacro(FileType
):
47 return "%s_LIST" % FileListMacro(FileType
)
49 class TargetDescBlock(object):
50 _Cache_
= {} # {TargetFile : TargetDescBlock object}
53 def __new__(Class
, Inputs
, Outputs
, Commands
, Dependencies
):
54 if Outputs
[0] in Class
._Cache
_:
55 Tdb
= Class
._Cache
_[Outputs
[0]]
59 Tdb
= super(TargetDescBlock
, Class
).__new
__(Class
)
60 Tdb
._Init
(Inputs
, Outputs
, Commands
, Dependencies
)
61 #Class._Cache_[Outputs[0]] = Tdb
64 def _Init(self
, Inputs
, Outputs
, Commands
, Dependencies
):
66 self
.Outputs
= Outputs
67 self
.Commands
= Commands
68 self
.Dependencies
= Dependencies
70 self
.Target
= self
.Outputs
[0]
75 return self
.Target
.Path
78 return hash(self
.Target
.Path
)
80 def __eq__(self
, Other
):
81 if type(Other
) == type(self
):
82 return Other
.Target
.Path
== self
.Target
.Path
84 return str(Other
) == self
.Target
.Path
86 def AddInput(self
, Input
):
87 if Input
not in self
.Inputs
:
88 self
.Inputs
.append(Input
)
90 def IsMultipleInput(self
):
91 return len(self
.Inputs
) > 1
95 TargetDescBlock
._Cache
_ = {}
97 ## Class for one build rule
99 # This represents a build rule which can give out corresponding command list for
100 # building the given source file(s). The result can be used for generating the
101 # target for makefile.
104 INC_LIST_MACRO
= "INC_LIST"
109 # @param Input The dictionary represeting input file(s) for a rule
110 # @param Output The list represeting output file(s) for a rule
111 # @param Command The list containing commands to generate the output from input
113 def __init__(self
, Type
, Input
, Output
, Command
, ExtraDependency
=None):
114 # The Input should not be empty
122 self
.FileListMacro
= FileListMacro(Type
)
123 self
.ListFileMacro
= ListFileMacro(Type
)
124 self
.IncListFileMacro
= self
.INC_LIST_MACRO
126 self
.SourceFileType
= Type
127 # source files listed not in "*" or "?" pattern format
128 if not ExtraDependency
:
129 self
.ExtraSourceFileList
= []
131 self
.ExtraSourceFileList
= ExtraDependency
134 # Search macros used in command lines for <FILE_TYPE>_LIST and INC_LIST.
135 # If found, generate a file to keep the input files used to get over the
136 # limitation of command line length
139 self
.CommandList
= []
140 for CmdLine
in Command
:
141 self
.MacroList
.extend(gMacroRefPattern
.findall(CmdLine
))
142 # replace path separator with native one
143 self
.CommandList
.append(CmdLine
)
145 # Indicate what should be generated
146 if self
.FileListMacro
in self
.MacroList
:
147 self
.GenFileListMacro
= True
149 self
.GenFileListMacro
= False
151 if self
.ListFileMacro
in self
.MacroList
:
152 self
.GenListFile
= True
153 self
.GenFileListMacro
= True
155 self
.GenListFile
= False
157 if self
.INC_LIST_MACRO
in self
.MacroList
:
158 self
.GenIncListFile
= True
160 self
.GenIncListFile
= False
163 self
.IsMultipleInput
= False
164 self
.SourceFileExtList
= []
166 Base
, Ext
= os
.path
.splitext(File
)
167 if Base
.find("*") >= 0:
168 # There's "*" in the file name
169 self
.IsMultipleInput
= True
170 self
.GenFileListMacro
= True
171 elif Base
.find("?") < 0:
172 # There's no "*" and "?" in file name
173 self
.ExtraSourceFileList
.append(File
)
175 if Ext
not in self
.SourceFileExtList
:
176 self
.SourceFileExtList
.append(Ext
)
179 self
.DestFileList
= []
181 self
.DestFileList
.append(File
)
183 # All build targets generated by this rule for a module
184 self
.BuildTargets
= {}
186 ## str() function support
192 SourceString
+= " %s %s %s" % (self
.SourceFileType
, " ".join(self
.SourceFileExtList
), self
.ExtraSourceFileList
)
193 DestString
= ", ".join(self
.DestFileList
)
194 CommandString
= "\n\t".join(self
.CommandList
)
195 return "%s : %s\n\t%s" % (DestString
, SourceString
, CommandString
)
197 ## Check if given file extension is supported by this rule
199 # @param FileExt The extension of a file
201 # @retval True If the extension is supported
202 # @retval False If the extension is not supported
204 def IsSupported(self
, FileExt
):
205 return FileExt
in self
.SourceFileExtList
207 def Instantiate(self
, Macros
={}):
208 NewRuleObject
= copy
.copy(self
)
209 NewRuleObject
.BuildTargets
= {}
210 NewRuleObject
.DestFileList
= []
211 for File
in self
.DestFileList
:
212 NewRuleObject
.DestFileList
.append(PathClass(NormPath(File
, Macros
)))
215 ## Apply the rule to given source file(s)
217 # @param SourceFile One file or a list of files to be built
218 # @param RelativeToDir The relative path of the source file
219 # @param PathSeparator Path separator
221 # @retval tuple (Source file in full path, List of individual sourcefiles, Destionation file, List of build commands)
223 def Apply(self
, SourceFile
, BuildRuleOrder
=None):
224 if not self
.CommandList
or not self
.DestFileList
:
228 if self
.IsMultipleInput
:
234 # SourceFile must be a list
235 SrcFile
= "$(%s)" % self
.FileListMacro
237 SrcFileName
, SrcFileBase
, SrcFileExt
= SourceFile
.Name
, SourceFile
.BaseName
, SourceFile
.Ext
239 SrcFileDir
= SourceFile
.SubDir
244 SrcFile
= SourceFile
.Path
245 SrcPath
= SourceFile
.Dir
247 # destination file (the first one)
248 if self
.DestFileList
:
249 DestFile
= self
.DestFileList
[0].Path
250 DestPath
= self
.DestFileList
[0].Dir
251 DestFileName
= self
.DestFileList
[0].Name
252 DestFileBase
, DestFileExt
= self
.DestFileList
[0].BaseName
, self
.DestFileList
[0].Ext
260 BuildRulePlaceholderDict
= {
264 "s_dir" : SrcFileDir
,
265 "s_name" : SrcFileName
,
266 "s_base" : SrcFileBase
,
267 "s_ext" : SrcFileExt
,
271 "d_name" : DestFileName
,
272 "d_base" : DestFileBase
,
273 "d_ext" : DestFileExt
,
277 for File
in self
.DestFileList
:
278 File
= string
.Template(str(File
)).safe_substitute(BuildRulePlaceholderDict
)
279 File
= string
.Template(str(File
)).safe_substitute(BuildRulePlaceholderDict
)
280 DstFile
.append(PathClass(File
, IsBinary
=True))
282 if DstFile
[0] in self
.BuildTargets
:
283 TargetDesc
= self
.BuildTargets
[DstFile
[0]]
284 if BuildRuleOrder
and SourceFile
.Ext
in BuildRuleOrder
:
285 Index
= BuildRuleOrder
.index(SourceFile
.Ext
)
286 for Input
in TargetDesc
.Inputs
:
287 if Input
.Ext
not in BuildRuleOrder
or BuildRuleOrder
.index(Input
.Ext
) > Index
:
289 # Command line should be regenerated since some macros are different
291 CommandList
= self
._BuildCommand
(BuildRulePlaceholderDict
)
292 TargetDesc
._Init
([SourceFile
], DstFile
, CommandList
, self
.ExtraSourceFileList
)
295 TargetDesc
.AddInput(SourceFile
)
297 CommandList
= self
._BuildCommand
(BuildRulePlaceholderDict
)
298 TargetDesc
= TargetDescBlock([SourceFile
], DstFile
, CommandList
, self
.ExtraSourceFileList
)
299 TargetDesc
.ListFileMacro
= self
.ListFileMacro
300 TargetDesc
.FileListMacro
= self
.FileListMacro
301 TargetDesc
.IncListFileMacro
= self
.IncListFileMacro
302 TargetDesc
.GenFileListMacro
= self
.GenFileListMacro
303 TargetDesc
.GenListFile
= self
.GenListFile
304 TargetDesc
.GenIncListFile
= self
.GenIncListFile
305 self
.BuildTargets
[DstFile
[0]] = TargetDesc
308 def _BuildCommand(self
, Macros
):
310 for CommandString
in self
.CommandList
:
311 CommandString
= string
.Template(CommandString
).safe_substitute(Macros
)
312 CommandString
= string
.Template(CommandString
).safe_substitute(Macros
)
313 CommandList
.append(CommandString
)
316 ## Class for build rules
318 # BuildRule class parses rules defined in a file or passed by caller, and converts
319 # the rule into FileBuildRule object.
322 _SectionHeader
= "SECTIONHEADER"
324 _SubSectionHeader
= "SUBSECTIONHEADER"
325 _SubSection
= "SUBSECTION"
326 _InputFile
= "INPUTFILE"
327 _OutputFile
= "OUTPUTFILE"
328 _ExtraDependency
= "EXTRADEPENDENCY"
330 _UnknownSection
= "UNKNOWNSECTION"
332 _SubSectionList
= [_InputFile
, _OutputFile
, _Command
]
335 _FileTypePattern
= re
.compile("^[_a-zA-Z][_\-0-9a-zA-Z]*$")
336 _BinaryFileRule
= FileBuildRule(TAB_DEFAULT_BINARY_FILE
, [], [os
.path
.join("$(OUTPUT_DIR)", "${s_name}")],
337 ["$(CP) ${src} ${dst}"], [])
341 # @param File The file containing build rules in a well defined format
342 # @param Content The string list of build rules in a well defined format
343 # @param LineIndex The line number from which the parsing will begin
344 # @param SupportedFamily The list of supported tool chain families
346 def __init__(self
, File
=None, Content
=None, LineIndex
=0, SupportedFamily
=["MSFT", "INTEL", "GCC", "RVCT"]):
348 # Read build rules from file if it's not none
351 self
.RuleContent
= open(File
, 'r').readlines()
353 EdkLogger
.error("build", FILE_OPEN_FAILURE
, ExtraData
=File
)
354 elif Content
!= None:
355 self
.RuleContent
= Content
357 EdkLogger
.error("build", PARAMETER_MISSING
, ExtraData
="No rule file or string given")
359 self
.SupportedToolChainFamilyList
= SupportedFamily
360 self
.RuleDatabase
= tdict(True, 4) # {FileExt, ModuleType, Arch, Family : FileBuildRule object}
361 self
.Ext2FileType
= {} # {ext : file-type}
362 self
.FileTypeList
= set()
364 self
._LineIndex
= LineIndex
366 self
._RuleInfo
= tdict(True, 2) # {toolchain family : {"InputFile": {}, "OutputFile" : [], "Command" : []}}
368 self
._BuildTypeList
= []
370 self
._FamilyList
= []
371 self
._TotalToolChainFamilySet
= set()
372 self
._RuleObjectList
= [] # FileBuildRule object list
373 self
._FileVersion
= ""
377 # some intrinsic rules
378 self
.RuleDatabase
[TAB_DEFAULT_BINARY_FILE
, "COMMON", "COMMON", "COMMON"] = self
._BinaryFileRule
379 self
.FileTypeList
.add(TAB_DEFAULT_BINARY_FILE
)
381 ## Parse the build rule strings
383 self
._State
= self
._Section
384 for Index
in range(self
._LineIndex
, len(self
.RuleContent
)):
385 # Clean up the line and replace path separator with native one
386 Line
= self
.RuleContent
[Index
].strip().replace(self
._PATH
_SEP
, os
.path
.sep
)
387 self
.RuleContent
[Index
] = Line
389 # find the build_rule_version
390 if Line
and Line
[0] == "#" and Line
.find(TAB_BUILD_RULE_VERSION
) <> -1:
391 if Line
.find("=") <> -1 and Line
.find("=") < (len(Line
) - 1) and (Line
[(Line
.find("=") + 1):]).split():
392 self
._FileVersion
= (Line
[(Line
.find("=") + 1):]).split()[0]
393 # skip empty or comment line
394 if Line
== "" or Line
[0] == "#":
397 # find out section header, enclosed by []
398 if Line
[0] == '[' and Line
[-1] == ']':
399 # merge last section information into rule database
401 self
._State
= self
._SectionHeader
402 # find out sub-section header, enclosed by <>
403 elif Line
[0] == '<' and Line
[-1] == '>':
404 if self
._State
!= self
._UnknownSection
:
405 self
._State
= self
._SubSectionHeader
407 # call section handler to parse each (sub)section
408 self
._StateHandler
[self
._State
](self
, Index
)
409 # merge last section information into rule database
412 ## Parse definitions under a section
414 # @param LineIndex The line index of build rule text
416 def ParseSection(self
, LineIndex
):
419 ## Parse definitions under a subsection
421 # @param LineIndex The line index of build rule text
423 def ParseSubSection(self
, LineIndex
):
424 # currenly nothing here
427 ## Placeholder for not supported sections
429 # @param LineIndex The line index of build rule text
431 def SkipSection(self
, LineIndex
):
434 ## Merge section information just got into rule database
435 def EndOfSection(self
):
436 Database
= self
.RuleDatabase
437 # if there's specific toochain family, 'COMMON' doesn't make sense any more
438 if len(self
._TotalToolChainFamilySet
) > 1 and 'COMMON' in self
._TotalToolChainFamilySet
:
439 self
._TotalToolChainFamilySet
.remove('COMMON')
440 for Family
in self
._TotalToolChainFamilySet
:
441 Input
= self
._RuleInfo
[Family
, self
._InputFile
]
442 Output
= self
._RuleInfo
[Family
, self
._OutputFile
]
443 Command
= self
._RuleInfo
[Family
, self
._Command
]
444 ExtraDependency
= self
._RuleInfo
[Family
, self
._ExtraDependency
]
446 BuildRule
= FileBuildRule(self
._FileType
, Input
, Output
, Command
, ExtraDependency
)
447 for BuildType
in self
._BuildTypeList
:
448 for Arch
in self
._ArchList
:
449 Database
[self
._FileType
, BuildType
, Arch
, Family
] = BuildRule
450 for FileExt
in BuildRule
.SourceFileExtList
:
451 self
.Ext2FileType
[FileExt
] = self
._FileType
453 ## Parse section header
455 # @param LineIndex The line index of build rule text
457 def ParseSectionHeader(self
, LineIndex
):
458 self
._RuleInfo
= tdict(True, 2)
459 self
._BuildTypeList
= []
461 self
._FamilyList
= []
462 self
._TotalToolChainFamilySet
= set()
464 RuleNameList
= self
.RuleContent
[LineIndex
][1:-1].split(',')
465 for RuleName
in RuleNameList
:
468 TokenList
= [Token
.strip().upper() for Token
in RuleName
.split('.')]
469 # old format: Build.File-Type
470 if TokenList
[0] == "BUILD":
471 if len(TokenList
) == 1:
472 EdkLogger
.error("build", FORMAT_INVALID
, "Invalid rule section",
473 File
=self
.RuleFile
, Line
=LineIndex
+ 1,
474 ExtraData
=self
.RuleContent
[LineIndex
])
476 FileType
= TokenList
[1]
478 EdkLogger
.error("build", FORMAT_INVALID
, "No file type given",
479 File
=self
.RuleFile
, Line
=LineIndex
+ 1,
480 ExtraData
=self
.RuleContent
[LineIndex
])
481 if self
._FileTypePattern
.match(FileType
) == None:
482 EdkLogger
.error("build", FORMAT_INVALID
, File
=self
.RuleFile
, Line
=LineIndex
+ 1,
483 ExtraData
="Only character, number (non-first character), '_' and '-' are allowed in file type")
484 # new format: File-Type.Build-Type.Arch
487 FileType
= TokenList
[0]
488 elif FileType
!= TokenList
[0]:
489 EdkLogger
.error("build", FORMAT_INVALID
,
490 "Different file types are not allowed in the same rule section",
491 File
=self
.RuleFile
, Line
=LineIndex
+ 1,
492 ExtraData
=self
.RuleContent
[LineIndex
])
493 if len(TokenList
) > 1:
494 BuildType
= TokenList
[1]
495 if len(TokenList
) > 2:
497 if BuildType
not in self
._BuildTypeList
:
498 self
._BuildTypeList
.append(BuildType
)
499 if Arch
not in self
._ArchList
:
500 self
._ArchList
.append(Arch
)
502 if 'COMMON' in self
._BuildTypeList
and len(self
._BuildTypeList
) > 1:
503 EdkLogger
.error("build", FORMAT_INVALID
,
504 "Specific build types must not be mixed with common one",
505 File
=self
.RuleFile
, Line
=LineIndex
+ 1,
506 ExtraData
=self
.RuleContent
[LineIndex
])
507 if 'COMMON' in self
._ArchList
and len(self
._ArchList
) > 1:
508 EdkLogger
.error("build", FORMAT_INVALID
,
509 "Specific ARCH must not be mixed with common one",
510 File
=self
.RuleFile
, Line
=LineIndex
+ 1,
511 ExtraData
=self
.RuleContent
[LineIndex
])
513 self
._FileType
= FileType
514 self
._State
= self
._Section
515 self
.FileTypeList
.add(FileType
)
517 ## Parse sub-section header
519 # @param LineIndex The line index of build rule text
521 def ParseSubSectionHeader(self
, LineIndex
):
523 List
= self
.RuleContent
[LineIndex
][1:-1].split(',')
526 TokenList
= Section
.split('.')
527 Type
= TokenList
[0].strip().upper()
529 if SectionType
== "":
531 elif SectionType
!= Type
:
532 EdkLogger
.error("build", FORMAT_INVALID
,
533 "Two different section types are not allowed in the same sub-section",
534 File
=self
.RuleFile
, Line
=LineIndex
+ 1,
535 ExtraData
=self
.RuleContent
[LineIndex
])
537 if len(TokenList
) > 1:
538 Family
= TokenList
[1].strip().upper()
542 if Family
not in FamilyList
:
543 FamilyList
.append(Family
)
545 self
._FamilyList
= FamilyList
546 self
._TotalToolChainFamilySet
.update(FamilyList
)
547 self
._State
= SectionType
.upper()
548 if 'COMMON' in FamilyList
and len(FamilyList
) > 1:
549 EdkLogger
.error("build", FORMAT_INVALID
,
550 "Specific tool chain family should not be mixed with general one",
551 File
=self
.RuleFile
, Line
=LineIndex
+ 1,
552 ExtraData
=self
.RuleContent
[LineIndex
])
553 if self
._State
not in self
._StateHandler
:
554 EdkLogger
.error("build", FORMAT_INVALID
, File
=self
.RuleFile
, Line
=LineIndex
+ 1,
555 ExtraData
="Unknown subsection: %s" % self
.RuleContent
[LineIndex
])
556 ## Parse <InputFile> sub-section
558 # @param LineIndex The line index of build rule text
560 def ParseInputFile(self
, LineIndex
):
561 FileList
= [File
.strip() for File
in self
.RuleContent
[LineIndex
].split(",")]
562 for ToolChainFamily
in self
._FamilyList
:
563 InputFiles
= self
._RuleInfo
[ToolChainFamily
, self
._State
]
564 if InputFiles
== None:
566 self
._RuleInfo
[ToolChainFamily
, self
._State
] = InputFiles
567 InputFiles
.extend(FileList
)
569 ## Parse <ExtraDependency> sub-section
571 # @param LineIndex The line index of build rule text
573 def ParseCommon(self
, LineIndex
):
574 for ToolChainFamily
in self
._FamilyList
:
575 Items
= self
._RuleInfo
[ToolChainFamily
, self
._State
]
578 self
._RuleInfo
[ToolChainFamily
, self
._State
] = Items
579 Items
.append(self
.RuleContent
[LineIndex
])
581 ## Get a build rule via [] operator
583 # @param FileExt The extension of a file
584 # @param ToolChainFamily The tool chain family name
585 # @param BuildVersion The build version number. "*" means any rule
588 # @retval FileType The file type string
589 # @retval FileBuildRule The object of FileBuildRule
591 # Key = (FileExt, ModuleType, Arch, ToolChainFamily)
592 def __getitem__(self
, Key
):
596 if Key
[0] in self
.Ext2FileType
:
597 Type
= self
.Ext2FileType
[Key
[0]]
598 elif Key
[0].upper() in self
.FileTypeList
:
599 Type
= Key
[0].upper()
604 Key
= (Type
,) + Key
[1:]
607 return self
.RuleDatabase
[Key
]
610 _SectionHeader
: ParseSectionHeader
,
611 _Section
: ParseSection
,
612 _SubSectionHeader
: ParseSubSectionHeader
,
613 _SubSection
: ParseSubSection
,
614 _InputFile
: ParseInputFile
,
615 _OutputFile
: ParseCommon
,
616 _ExtraDependency
: ParseCommon
,
617 _Command
: ParseCommon
,
618 _UnknownSection
: SkipSection
,
621 # This acts like the main() function for the script, unless it is 'import'ed into another
623 if __name__
== '__main__':
625 EdkLogger
.Initialize()
626 if len(sys
.argv
) > 1:
627 Br
= BuildRule(sys
.argv
[1])
628 print str(Br
[".c", "DXE_DRIVER", "IA32", "MSFT"][1])
630 print str(Br
[".c", "DXE_DRIVER", "IA32", "INTEL"][1])
632 print str(Br
[".c", "DXE_DRIVER", "IA32", "GCC"][1])
634 print str(Br
[".ac", "ACPI_TABLE", "IA32", "MSFT"][1])
636 print str(Br
[".h", "ACPI_TABLE", "IA32", "INTEL"][1])
638 print str(Br
[".ac", "ACPI_TABLE", "IA32", "MSFT"][1])
640 print str(Br
[".s", "SEC", "IPF", "COMMON"][1])
642 print str(Br
[".s", "SEC"][1])