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
):
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 TargetDesc
.AddInput(SourceFile
)
287 for CommandString
in self
.CommandList
:
288 CommandString
= string
.Template(CommandString
).safe_substitute(BuildRulePlaceholderDict
)
289 CommandString
= string
.Template(CommandString
).safe_substitute(BuildRulePlaceholderDict
)
290 CommandList
.append(CommandString
)
291 TargetDesc
= TargetDescBlock([SourceFile
], DstFile
, CommandList
, self
.ExtraSourceFileList
)
292 TargetDesc
.ListFileMacro
= self
.ListFileMacro
293 TargetDesc
.FileListMacro
= self
.FileListMacro
294 TargetDesc
.IncListFileMacro
= self
.IncListFileMacro
295 TargetDesc
.GenFileListMacro
= self
.GenFileListMacro
296 TargetDesc
.GenListFile
= self
.GenListFile
297 TargetDesc
.GenIncListFile
= self
.GenIncListFile
298 self
.BuildTargets
[DstFile
[0]] = TargetDesc
301 ## Class for build rules
303 # BuildRule class parses rules defined in a file or passed by caller, and converts
304 # the rule into FileBuildRule object.
307 _SectionHeader
= "SECTIONHEADER"
309 _SubSectionHeader
= "SUBSECTIONHEADER"
310 _SubSection
= "SUBSECTION"
311 _InputFile
= "INPUTFILE"
312 _OutputFile
= "OUTPUTFILE"
313 _ExtraDependency
= "EXTRADEPENDENCY"
315 _UnknownSection
= "UNKNOWNSECTION"
317 _SubSectionList
= [_InputFile
, _OutputFile
, _Command
]
320 _FileTypePattern
= re
.compile("^[_a-zA-Z][_\-0-9a-zA-Z]*$")
321 _BinaryFileRule
= FileBuildRule(TAB_DEFAULT_BINARY_FILE
, [], [os
.path
.join("$(OUTPUT_DIR)", "${s_name}")],
322 ["$(CP) ${src} ${dst}"], [])
326 # @param File The file containing build rules in a well defined format
327 # @param Content The string list of build rules in a well defined format
328 # @param LineIndex The line number from which the parsing will begin
329 # @param SupportedFamily The list of supported tool chain families
331 def __init__(self
, File
=None, Content
=None, LineIndex
=0, SupportedFamily
=["MSFT", "INTEL", "GCC", "RVCT"]):
333 # Read build rules from file if it's not none
336 self
.RuleContent
= open(File
, 'r').readlines()
338 EdkLogger
.error("build", FILE_OPEN_FAILURE
, ExtraData
=File
)
339 elif Content
!= None:
340 self
.RuleContent
= Content
342 EdkLogger
.error("build", PARAMETER_MISSING
, ExtraData
="No rule file or string given")
344 self
.SupportedToolChainFamilyList
= SupportedFamily
345 self
.RuleDatabase
= tdict(True, 4) # {FileExt, ModuleType, Arch, Family : FileBuildRule object}
346 self
.Ext2FileType
= {} # {ext : file-type}
347 self
.FileTypeList
= set()
349 self
._LineIndex
= LineIndex
351 self
._RuleInfo
= tdict(True, 2) # {toolchain family : {"InputFile": {}, "OutputFile" : [], "Command" : []}}
353 self
._BuildTypeList
= []
355 self
._FamilyList
= []
356 self
._TotalToolChainFamilySet
= set()
357 self
._RuleObjectList
= [] # FileBuildRule object list
358 self
._FileVersion
= ""
362 # some intrinsic rules
363 self
.RuleDatabase
[TAB_DEFAULT_BINARY_FILE
, "COMMON", "COMMON", "COMMON"] = self
._BinaryFileRule
364 self
.FileTypeList
.add(TAB_DEFAULT_BINARY_FILE
)
366 ## Parse the build rule strings
368 self
._State
= self
._Section
369 for Index
in range(self
._LineIndex
, len(self
.RuleContent
)):
370 # Clean up the line and replace path separator with native one
371 Line
= self
.RuleContent
[Index
].strip().replace(self
._PATH
_SEP
, os
.path
.sep
)
372 self
.RuleContent
[Index
] = Line
374 # find the build_rule_version
375 if Line
and Line
[0] == "#" and Line
.find(TAB_BUILD_RULE_VERSION
) <> -1:
376 if Line
.find("=") <> -1 and Line
.find("=") < (len(Line
)-1) and (Line
[(Line
.find("=") + 1):]).split():
377 self
._FileVersion
= (Line
[(Line
.find("=") + 1):]).split()[0]
378 # skip empty or comment line
379 if Line
== "" or Line
[0] == "#":
382 # find out section header, enclosed by []
383 if Line
[0] == '[' and Line
[-1] == ']':
384 # merge last section information into rule database
386 self
._State
= self
._SectionHeader
387 # find out sub-section header, enclosed by <>
388 elif Line
[0] == '<' and Line
[-1] == '>':
389 if self
._State
!= self
._UnknownSection
:
390 self
._State
= self
._SubSectionHeader
392 # call section handler to parse each (sub)section
393 self
._StateHandler
[self
._State
](self
, Index
)
394 # merge last section information into rule database
397 ## Parse definitions under a section
399 # @param LineIndex The line index of build rule text
401 def ParseSection(self
, LineIndex
):
404 ## Parse definitions under a subsection
406 # @param LineIndex The line index of build rule text
408 def ParseSubSection(self
, LineIndex
):
409 # currenly nothing here
412 ## Placeholder for not supported sections
414 # @param LineIndex The line index of build rule text
416 def SkipSection(self
, LineIndex
):
419 ## Merge section information just got into rule database
420 def EndOfSection(self
):
421 Database
= self
.RuleDatabase
422 # if there's specific toochain family, 'COMMON' doesn't make sense any more
423 if len(self
._TotalToolChainFamilySet
) > 1 and 'COMMON' in self
._TotalToolChainFamilySet
:
424 self
._TotalToolChainFamilySet
.remove('COMMON')
425 for Family
in self
._TotalToolChainFamilySet
:
426 Input
= self
._RuleInfo
[Family
, self
._InputFile
]
427 Output
= self
._RuleInfo
[Family
, self
._OutputFile
]
428 Command
= self
._RuleInfo
[Family
, self
._Command
]
429 ExtraDependency
= self
._RuleInfo
[Family
, self
._ExtraDependency
]
431 BuildRule
= FileBuildRule(self
._FileType
, Input
, Output
, Command
, ExtraDependency
)
432 for BuildType
in self
._BuildTypeList
:
433 for Arch
in self
._ArchList
:
434 Database
[self
._FileType
, BuildType
, Arch
, Family
] = BuildRule
435 for FileExt
in BuildRule
.SourceFileExtList
:
436 self
.Ext2FileType
[FileExt
] = self
._FileType
438 ## Parse section header
440 # @param LineIndex The line index of build rule text
442 def ParseSectionHeader(self
, LineIndex
):
443 self
._RuleInfo
= tdict(True, 2)
444 self
._BuildTypeList
= []
446 self
._FamilyList
= []
447 self
._TotalToolChainFamilySet
= set()
449 RuleNameList
= self
.RuleContent
[LineIndex
][1:-1].split(',')
450 for RuleName
in RuleNameList
:
453 TokenList
= [Token
.strip().upper() for Token
in RuleName
.split('.')]
454 # old format: Build.File-Type
455 if TokenList
[0] == "BUILD":
456 if len(TokenList
) == 1:
457 EdkLogger
.error("build", FORMAT_INVALID
, "Invalid rule section",
458 File
=self
.RuleFile
, Line
=LineIndex
+1,
459 ExtraData
=self
.RuleContent
[LineIndex
])
461 FileType
= TokenList
[1]
463 EdkLogger
.error("build", FORMAT_INVALID
, "No file type given",
464 File
=self
.RuleFile
, Line
=LineIndex
+1,
465 ExtraData
=self
.RuleContent
[LineIndex
])
466 if self
._FileTypePattern
.match(FileType
) == None:
467 EdkLogger
.error("build", FORMAT_INVALID
, File
=self
.RuleFile
, Line
=LineIndex
+1,
468 ExtraData
="Only character, number (non-first character), '_' and '-' are allowed in file type")
469 # new format: File-Type.Build-Type.Arch
472 FileType
= TokenList
[0]
473 elif FileType
!= TokenList
[0]:
474 EdkLogger
.error("build", FORMAT_INVALID
,
475 "Different file types are not allowed in the same rule section",
476 File
=self
.RuleFile
, Line
=LineIndex
+1,
477 ExtraData
=self
.RuleContent
[LineIndex
])
478 if len(TokenList
) > 1:
479 BuildType
= TokenList
[1]
480 if len(TokenList
) > 2:
482 if BuildType
not in self
._BuildTypeList
:
483 self
._BuildTypeList
.append(BuildType
)
484 if Arch
not in self
._ArchList
:
485 self
._ArchList
.append(Arch
)
487 if 'COMMON' in self
._BuildTypeList
and len(self
._BuildTypeList
) > 1:
488 EdkLogger
.error("build", FORMAT_INVALID
,
489 "Specific build types must not be mixed with common one",
490 File
=self
.RuleFile
, Line
=LineIndex
+1,
491 ExtraData
=self
.RuleContent
[LineIndex
])
492 if 'COMMON' in self
._ArchList
and len(self
._ArchList
) > 1:
493 EdkLogger
.error("build", FORMAT_INVALID
,
494 "Specific ARCH must not be mixed with common one",
495 File
=self
.RuleFile
, Line
=LineIndex
+1,
496 ExtraData
=self
.RuleContent
[LineIndex
])
498 self
._FileType
= FileType
499 self
._State
= self
._Section
500 self
.FileTypeList
.add(FileType
)
502 ## Parse sub-section header
504 # @param LineIndex The line index of build rule text
506 def ParseSubSectionHeader(self
, LineIndex
):
508 List
= self
.RuleContent
[LineIndex
][1:-1].split(',')
511 TokenList
= Section
.split('.')
512 Type
= TokenList
[0].strip().upper()
514 if SectionType
== "":
516 elif SectionType
!= Type
:
517 EdkLogger
.error("build", FORMAT_INVALID
,
518 "Two different section types are not allowed in the same sub-section",
519 File
=self
.RuleFile
, Line
=LineIndex
+1,
520 ExtraData
=self
.RuleContent
[LineIndex
])
522 if len(TokenList
) > 1:
523 Family
= TokenList
[1].strip().upper()
527 if Family
not in FamilyList
:
528 FamilyList
.append(Family
)
530 self
._FamilyList
= FamilyList
531 self
._TotalToolChainFamilySet
.update(FamilyList
)
532 self
._State
= SectionType
.upper()
533 if 'COMMON' in FamilyList
and len(FamilyList
) > 1:
534 EdkLogger
.error("build", FORMAT_INVALID
,
535 "Specific tool chain family should not be mixed with general one",
536 File
=self
.RuleFile
, Line
=LineIndex
+1,
537 ExtraData
=self
.RuleContent
[LineIndex
])
538 if self
._State
not in self
._StateHandler
:
539 EdkLogger
.error("build", FORMAT_INVALID
, File
=self
.RuleFile
, Line
=LineIndex
+1,
540 ExtraData
="Unknown subsection: %s" % self
.RuleContent
[LineIndex
])
541 ## Parse <InputFile> sub-section
543 # @param LineIndex The line index of build rule text
545 def ParseInputFile(self
, LineIndex
):
546 FileList
= [File
.strip() for File
in self
.RuleContent
[LineIndex
].split(",")]
547 for ToolChainFamily
in self
._FamilyList
:
548 InputFiles
= self
._RuleInfo
[ToolChainFamily
, self
._State
]
549 if InputFiles
== None:
551 self
._RuleInfo
[ToolChainFamily
, self
._State
] = InputFiles
552 InputFiles
.extend(FileList
)
554 ## Parse <ExtraDependency> sub-section
556 # @param LineIndex The line index of build rule text
558 def ParseCommon(self
, LineIndex
):
559 for ToolChainFamily
in self
._FamilyList
:
560 Items
= self
._RuleInfo
[ToolChainFamily
, self
._State
]
563 self
._RuleInfo
[ToolChainFamily
, self
._State
] = Items
564 Items
.append(self
.RuleContent
[LineIndex
])
566 ## Get a build rule via [] operator
568 # @param FileExt The extension of a file
569 # @param ToolChainFamily The tool chain family name
570 # @param BuildVersion The build version number. "*" means any rule
573 # @retval FileType The file type string
574 # @retval FileBuildRule The object of FileBuildRule
576 # Key = (FileExt, ModuleType, Arch, ToolChainFamily)
577 def __getitem__(self
, Key
):
581 if Key
[0] in self
.Ext2FileType
:
582 Type
= self
.Ext2FileType
[Key
[0]]
583 elif Key
[0].upper() in self
.FileTypeList
:
584 Type
= Key
[0].upper()
589 Key
= (Type
,) + Key
[1:]
592 return self
.RuleDatabase
[Key
]
595 _SectionHeader
: ParseSectionHeader
,
596 _Section
: ParseSection
,
597 _SubSectionHeader
: ParseSubSectionHeader
,
598 _SubSection
: ParseSubSection
,
599 _InputFile
: ParseInputFile
,
600 _OutputFile
: ParseCommon
,
601 _ExtraDependency
: ParseCommon
,
602 _Command
: ParseCommon
,
603 _UnknownSection
: SkipSection
,
606 # This acts like the main() function for the script, unless it is 'import'ed into another
608 if __name__
== '__main__':
610 EdkLogger
.Initialize()
611 if len(sys
.argv
) > 1:
612 Br
= BuildRule(sys
.argv
[1])
613 print str(Br
[".c", "DXE_DRIVER", "IA32", "MSFT"][1])
615 print str(Br
[".c", "DXE_DRIVER", "IA32", "INTEL"][1])
617 print str(Br
[".c", "DXE_DRIVER", "IA32", "GCC"][1])
619 print str(Br
[".ac", "ACPI_TABLE", "IA32", "MSFT"][1])
621 print str(Br
[".h", "ACPI_TABLE", "IA32", "INTEL"][1])
623 print str(Br
[".ac", "ACPI_TABLE", "IA32", "MSFT"][1])
625 print str(Br
[".s", "SEC", "IPF", "COMMON"][1])
627 print str(Br
[".s", "SEC"][1])