2 # This file is used to be the main entrance of ECC tool
4 # Copyright (c) 2009 - 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
, time
, glob
, sys
18 import Common
.EdkLogger
as EdkLogger
21 from MetaDataParser
import *
22 from optparse
import OptionParser
23 from Configuration
import Configuration
24 from Check
import Check
25 import Common
.GlobalData
as GlobalData
27 from Common
.String
import NormPath
28 from Common
.BuildVersion
import gBUILD_VERSION
29 from Common
import BuildToolError
30 from Common
.Misc
import PathClass
31 from Common
.Misc
import DirCache
32 from MetaFileWorkspace
.MetaFileParser
import DscParser
33 from MetaFileWorkspace
.MetaFileParser
import DecParser
34 from MetaFileWorkspace
.MetaFileParser
import InfParser
35 from MetaFileWorkspace
.MetaFileParser
import Fdf
36 from MetaFileWorkspace
.MetaFileTable
import MetaFileStorage
39 from Exception import *
40 from Common
.LongFilePathSupport
import OpenLongFilePath
as open
41 from Common
.MultipleWorkspace
import MultipleWorkspace
as mws
45 # This class is used to define Ecc main entrance
47 # @param object: Inherited from object class
51 # Version and Copyright
52 self
.VersionNumber
= ("0.01" + " " + gBUILD_VERSION
)
53 self
.Version
= "%prog Version " + self
.VersionNumber
54 self
.Copyright
= "Copyright (c) 2009 - 2010, Intel Corporation All rights reserved."
56 self
.InitDefaultConfigIni()
57 self
.OutputFile
= 'output.txt'
58 self
.ReportFile
= 'Report.csv'
59 self
.ExceptionFile
= 'exception.xml'
61 self
.ScanSourceCode
= True
62 self
.ScanMetaData
= True
66 # Parse the options and args
70 # Check EFI_SOURCE (Edk build convention). EDK_SOURCE will always point to ECP
72 WorkspaceDir
= os
.path
.normcase(os
.path
.normpath(os
.environ
["WORKSPACE"]))
73 os
.environ
["WORKSPACE"] = WorkspaceDir
75 # set multiple workspace
76 PackagesPath
= os
.getenv("PACKAGES_PATH")
77 mws
.setWs(WorkspaceDir
, PackagesPath
)
79 if "ECP_SOURCE" not in os
.environ
:
80 os
.environ
["ECP_SOURCE"] = mws
.join(WorkspaceDir
, GlobalData
.gEdkCompatibilityPkg
)
81 if "EFI_SOURCE" not in os
.environ
:
82 os
.environ
["EFI_SOURCE"] = os
.environ
["ECP_SOURCE"]
83 if "EDK_SOURCE" not in os
.environ
:
84 os
.environ
["EDK_SOURCE"] = os
.environ
["ECP_SOURCE"]
87 # Unify case of characters on case-insensitive systems
89 EfiSourceDir
= os
.path
.normcase(os
.path
.normpath(os
.environ
["EFI_SOURCE"]))
90 EdkSourceDir
= os
.path
.normcase(os
.path
.normpath(os
.environ
["EDK_SOURCE"]))
91 EcpSourceDir
= os
.path
.normcase(os
.path
.normpath(os
.environ
["ECP_SOURCE"]))
93 os
.environ
["EFI_SOURCE"] = EfiSourceDir
94 os
.environ
["EDK_SOURCE"] = EdkSourceDir
95 os
.environ
["ECP_SOURCE"] = EcpSourceDir
97 GlobalData
.gWorkspace
= WorkspaceDir
98 GlobalData
.gEfiSource
= EfiSourceDir
99 GlobalData
.gEdkSource
= EdkSourceDir
100 GlobalData
.gEcpSource
= EcpSourceDir
102 GlobalData
.gGlobalDefines
["WORKSPACE"] = WorkspaceDir
103 GlobalData
.gGlobalDefines
["EFI_SOURCE"] = EfiSourceDir
104 GlobalData
.gGlobalDefines
["EDK_SOURCE"] = EdkSourceDir
105 GlobalData
.gGlobalDefines
["ECP_SOURCE"] = EcpSourceDir
108 # Generate checkpoints list
109 EccGlobalData
.gConfig
= Configuration(self
.ConfigFile
)
111 # Generate exception list
112 EccGlobalData
.gException
= ExceptionCheck(self
.ExceptionFile
)
115 EccGlobalData
.gDb
= Database
.Database(Database
.DATABASE_PATH
)
116 EccGlobalData
.gDb
.InitDatabase(self
.IsInit
)
119 # Get files real name in workspace dir
121 GlobalData
.gAllFiles
= DirCache(GlobalData
.gWorkspace
)
124 # self.BuildDatabase()
125 self
.DetectOnlyScanDirs()
134 EccGlobalData
.gDb
.Close()
136 def InitDefaultConfigIni(self
):
137 paths
= map(lambda p
: os
.path
.join(p
, 'Ecc', 'config.ini'), sys
.path
)
138 paths
= (os
.path
.realpath('config.ini'),) + tuple(paths
)
140 if os
.path
.exists(path
):
141 self
.ConfigFile
= path
143 self
.ConfigFile
= 'config.ini'
148 # Detect whether only scanned folders have been enabled
150 def DetectOnlyScanDirs(self
):
151 if self
.OnlyScan
== True:
153 # Use regex here if multiple spaces or TAB exists in ScanOnlyDirList in config.ini file
154 for folder
in re
.finditer(r
'\S+', EccGlobalData
.gConfig
.ScanOnlyDirList
):
155 OnlyScanDirs
.append(folder
.group())
156 if len(OnlyScanDirs
) != 0:
157 self
.BuildDatabase(OnlyScanDirs
)
159 EdkLogger
.error("ECC", BuildToolError
.OPTION_VALUE_INVALID
, ExtraData
="Use -f option need to fill specific folders in config.ini file")
166 # Build the database for target
168 def BuildDatabase(self
, SpeciDirs
= None):
170 EccGlobalData
.gDb
.TblReport
.Drop()
171 EccGlobalData
.gDb
.TblReport
.Create()
175 if self
.ScanMetaData
:
176 EdkLogger
.quiet("Building database for Meta Data File ...")
177 self
.BuildMetaDataFileDatabase(SpeciDirs
)
178 if self
.ScanSourceCode
:
179 EdkLogger
.quiet("Building database for Meta Data File Done!")
180 if SpeciDirs
== None:
181 c
.CollectSourceCodeDataIntoDB(EccGlobalData
.gTarget
)
183 for specificDir
in SpeciDirs
:
184 c
.CollectSourceCodeDataIntoDB(os
.path
.join(EccGlobalData
.gTarget
, specificDir
))
186 EccGlobalData
.gIdentifierTableList
= GetTableList((MODEL_FILE_C
, MODEL_FILE_H
), 'Identifier', EccGlobalData
.gDb
)
187 EccGlobalData
.gCFileList
= GetFileList(MODEL_FILE_C
, EccGlobalData
.gDb
)
188 EccGlobalData
.gHFileList
= GetFileList(MODEL_FILE_H
, EccGlobalData
.gDb
)
189 EccGlobalData
.gUFileList
= GetFileList(MODEL_FILE_UNI
, EccGlobalData
.gDb
)
191 ## BuildMetaDataFileDatabase
193 # Build the database for meta data files
195 def BuildMetaDataFileDatabase(self
, SpecificDirs
= None):
197 if SpecificDirs
== None:
198 ScanFolders
.append(EccGlobalData
.gTarget
)
200 for specificDir
in SpecificDirs
:
201 ScanFolders
.append(os
.path
.join(EccGlobalData
.gTarget
, specificDir
))
202 EdkLogger
.quiet("Building database for meta data files ...")
203 Op
= open(EccGlobalData
.gConfig
.MetaDataFileCheckPathOfGenerateFileList
, 'w+')
204 #SkipDirs = Read from config file
205 SkipDirs
= EccGlobalData
.gConfig
.SkipDirList
206 SkipDirString
= string
.join(SkipDirs
, '|')
207 # p = re.compile(r'.*[\\/](?:%s)[\\/]?.*' % SkipDirString)
208 p
= re
.compile(r
'.*[\\/](?:%s^\S)[\\/]?.*' % SkipDirString
)
209 for scanFolder
in ScanFolders
:
210 for Root
, Dirs
, Files
in os
.walk(scanFolder
):
211 if p
.match(Root
.upper()):
214 Dirname
= os
.path
.join(Root
, Dir
)
215 if os
.path
.islink(Dirname
):
216 Dirname
= os
.path
.realpath(Dirname
)
217 if os
.path
.isdir(Dirname
):
218 # symlinks to directories are treated as directories
223 if len(File
) > 4 and File
[-4:].upper() == ".DEC":
224 Filename
= os
.path
.normpath(os
.path
.join(Root
, File
))
225 EdkLogger
.quiet("Parsing %s" % Filename
)
226 Op
.write("%s\r" % Filename
)
227 #Dec(Filename, True, True, EccGlobalData.gWorkspace, EccGlobalData.gDb)
228 self
.MetaFile
= DecParser(Filename
, MODEL_FILE_DEC
, EccGlobalData
.gDb
.TblDec
)
229 self
.MetaFile
.Start()
231 if len(File
) > 4 and File
[-4:].upper() == ".DSC":
232 Filename
= os
.path
.normpath(os
.path
.join(Root
, File
))
233 EdkLogger
.quiet("Parsing %s" % Filename
)
234 Op
.write("%s\r" % Filename
)
235 #Dsc(Filename, True, True, EccGlobalData.gWorkspace, EccGlobalData.gDb)
236 self
.MetaFile
= DscParser(PathClass(Filename
, Root
), MODEL_FILE_DSC
, MetaFileStorage(EccGlobalData
.gDb
.TblDsc
.Cur
, Filename
, MODEL_FILE_DSC
, True))
237 # alwasy do post-process, in case of macros change
238 self
.MetaFile
.DoPostProcess()
239 self
.MetaFile
.Start()
240 self
.MetaFile
._PostProcess
()
242 if len(File
) > 4 and File
[-4:].upper() == ".INF":
243 Filename
= os
.path
.normpath(os
.path
.join(Root
, File
))
244 EdkLogger
.quiet("Parsing %s" % Filename
)
245 Op
.write("%s\r" % Filename
)
246 #Inf(Filename, True, True, EccGlobalData.gWorkspace, EccGlobalData.gDb)
247 self
.MetaFile
= InfParser(Filename
, MODEL_FILE_INF
, EccGlobalData
.gDb
.TblInf
)
248 self
.MetaFile
.Start()
250 if len(File
) > 4 and File
[-4:].upper() == ".FDF":
251 Filename
= os
.path
.normpath(os
.path
.join(Root
, File
))
252 EdkLogger
.quiet("Parsing %s" % Filename
)
253 Op
.write("%s\r" % Filename
)
254 Fdf(Filename
, True, EccGlobalData
.gWorkspace
, EccGlobalData
.gDb
)
256 if len(File
) > 4 and File
[-4:].upper() == ".UNI":
257 Filename
= os
.path
.normpath(os
.path
.join(Root
, File
))
258 EdkLogger
.quiet("Parsing %s" % Filename
)
259 Op
.write("%s\r" % Filename
)
260 FileID
= EccGlobalData
.gDb
.TblFile
.InsertFile(Filename
, MODEL_FILE_UNI
)
261 EccGlobalData
.gDb
.TblReport
.UpdateBelongsToItemByFile(FileID
, File
)
267 EccGlobalData
.gDb
.Conn
.commit()
269 EdkLogger
.quiet("Building database for meta data files done!")
273 # Check each checkpoint
276 EdkLogger
.quiet("Checking ...")
279 EdkLogger
.quiet("Checking done!")
283 # Generate the scan report
286 EdkLogger
.quiet("Generating report ...")
287 EccGlobalData
.gDb
.TblReport
.ToCSV(self
.ReportFile
)
288 EdkLogger
.quiet("Generating report done!")
290 def GetRealPathCase(self
, path
):
291 TmpPath
= path
.rstrip(os
.sep
)
292 PathParts
= TmpPath
.split(os
.sep
)
293 if len(PathParts
) == 0:
295 if len(PathParts
) == 1:
296 if PathParts
[0].strip().endswith(':'):
297 return PathParts
[0].upper()
298 # Relative dir, list . current dir
299 Dirs
= os
.listdir('.')
301 if Dir
.upper() == PathParts
[0].upper():
304 if PathParts
[0].strip().endswith(':'):
305 PathParts
[0] = PathParts
[0].upper()
306 ParentDir
= PathParts
[0]
308 if PathParts
[0] == '':
312 PathParts
.remove(PathParts
[0]) # need to remove the parent
313 for Part
in PathParts
:
314 Dirs
= os
.listdir(ParentDir
+ os
.sep
)
316 if Dir
.upper() == Part
.upper():
329 def ParseOption(self
):
330 EdkLogger
.quiet("Loading ECC configuration ... done")
331 (Options
, Target
) = self
.EccOptionParser()
333 if Options
.Workspace
:
334 os
.environ
["WORKSPACE"] = Options
.Workspace
336 # Check workspace envirnoment
337 if "WORKSPACE" not in os
.environ
:
338 EdkLogger
.error("ECC", BuildToolError
.ATTRIBUTE_NOT_AVAILABLE
, "Environment variable not found",
339 ExtraData
="WORKSPACE")
341 EccGlobalData
.gWorkspace
= os
.path
.normpath(os
.getenv("WORKSPACE"))
342 if not os
.path
.exists(EccGlobalData
.gWorkspace
):
343 EdkLogger
.error("ECC", BuildToolError
.FILE_NOT_FOUND
, ExtraData
="WORKSPACE = %s" % EccGlobalData
.gWorkspace
)
344 os
.environ
["WORKSPACE"] = EccGlobalData
.gWorkspace
346 self
.SetLogLevel(Options
)
349 if Options
.ConfigFile
!= None:
350 self
.ConfigFile
= Options
.ConfigFile
351 if Options
.OutputFile
!= None:
352 self
.OutputFile
= Options
.OutputFile
353 if Options
.ReportFile
!= None:
354 self
.ReportFile
= Options
.ReportFile
355 if Options
.ExceptionFile
!= None:
356 self
.ExceptionFile
= Options
.ExceptionFile
357 if Options
.Target
!= None:
358 if not os
.path
.isdir(Options
.Target
):
359 EdkLogger
.error("ECC", BuildToolError
.OPTION_VALUE_INVALID
, ExtraData
="Target [%s] does NOT exist" % Options
.Target
)
361 EccGlobalData
.gTarget
= self
.GetRealPathCase(os
.path
.normpath(Options
.Target
))
363 EdkLogger
.warn("Ecc", EdkLogger
.ECC_ERROR
, "The target source tree was not specified, using current WORKSPACE instead!")
364 EccGlobalData
.gTarget
= os
.path
.normpath(os
.getenv("WORKSPACE"))
365 if Options
.keepdatabase
!= None:
367 if Options
.metadata
!= None and Options
.sourcecode
!= None:
368 EdkLogger
.error("ECC", BuildToolError
.OPTION_CONFLICT
, ExtraData
="-m and -s can't be specified at one time")
369 if Options
.metadata
!= None:
370 self
.ScanSourceCode
= False
371 if Options
.sourcecode
!= None:
372 self
.ScanMetaData
= False
373 if Options
.folders
!= None:
378 # Set current log level of the tool based on args
380 # @param Option: The option list including log level setting
382 def SetLogLevel(self
, Option
):
383 if Option
.verbose
!= None:
384 EdkLogger
.SetLevel(EdkLogger
.VERBOSE
)
385 elif Option
.quiet
!= None:
386 EdkLogger
.SetLevel(EdkLogger
.QUIET
)
387 elif Option
.debug
!= None:
388 EdkLogger
.SetLevel(Option
.debug
+ 1)
390 EdkLogger
.SetLevel(EdkLogger
.INFO
)
392 ## Parse command line options
394 # Using standard Python module optparse to parse command line option of this tool.
396 # @retval Opt A optparse.Values object containing the parsed options
397 # @retval Args Target of build command
399 def EccOptionParser(self
):
400 Parser
= OptionParser(description
= self
.Copyright
, version
= self
.Version
, prog
= "Ecc.exe", usage
= "%prog [options]")
401 Parser
.add_option("-t", "--target sourcepath", action
="store", type="string", dest
='Target',
402 help="Check all files under the target workspace.")
403 Parser
.add_option("-c", "--config filename", action
="store", type="string", dest
="ConfigFile",
404 help="Specify a configuration file. Defaultly use config.ini under ECC tool directory.")
405 Parser
.add_option("-o", "--outfile filename", action
="store", type="string", dest
="OutputFile",
406 help="Specify the name of an output file, if and only if one filename was specified.")
407 Parser
.add_option("-r", "--reportfile filename", action
="store", type="string", dest
="ReportFile",
408 help="Specify the name of an report file, if and only if one filename was specified.")
409 Parser
.add_option("-e", "--exceptionfile filename", action
="store", type="string", dest
="ExceptionFile",
410 help="Specify the name of an exception file, if and only if one filename was specified.")
411 Parser
.add_option("-m", "--metadata", action
="store_true", type=None, help="Only scan meta-data files information if this option is specified.")
412 Parser
.add_option("-s", "--sourcecode", action
="store_true", type=None, help="Only scan source code files information if this option is specified.")
413 Parser
.add_option("-k", "--keepdatabase", action
="store_true", type=None, help="The existing Ecc database will not be cleaned except report information if this option is specified.")
414 Parser
.add_option("-l", "--log filename", action
="store", dest
="LogFile", help="""If specified, the tool should emit the changes that
415 were made by the tool after printing the result message.
416 If filename, the emit to the file, otherwise emit to
417 standard output. If no modifications were made, then do not
418 create a log file, or output a log message.""")
419 Parser
.add_option("-q", "--quiet", action
="store_true", type=None, help="Disable all messages except FATAL ERRORS.")
420 Parser
.add_option("-v", "--verbose", action
="store_true", type=None, help="Turn on verbose output with informational messages printed, "\
421 "including library instances selected, final dependency expression, "\
422 "and warning messages, etc.")
423 Parser
.add_option("-d", "--debug", action
="store", type="int", help="Enable debug messages at specified level.")
424 Parser
.add_option("-w", "--workspace", action
="store", type="string", dest
='Workspace', help="Specify workspace.")
425 Parser
.add_option("-f", "--folders", action
="store_true", type=None, help="Only scanning specified folders which are recorded in config.ini file.")
427 (Opt
, Args
)=Parser
.parse_args()
433 # This acts like the main() function for the script, unless it is 'import'ed into another
436 if __name__
== '__main__':
437 # Initialize log system
438 EdkLogger
.Initialize()
439 EdkLogger
.IsRaiseError
= False
440 EdkLogger
.quiet(time
.strftime("%H:%M:%S, %b.%d %Y ", time
.localtime()) + "[00:00]" + "\n")
442 StartTime
= time
.clock()
444 FinishTime
= time
.clock()
446 BuildDuration
= time
.strftime("%M:%S", time
.gmtime(int(round(FinishTime
- StartTime
))))
447 EdkLogger
.quiet("\n%s [%s]" % (time
.strftime("%H:%M:%S, %b.%d %Y", time
.localtime()), BuildDuration
))