BaseTools: Use absolute import in Ecc
[mirror_edk2.git] / BaseTools / Source / Python / Ecc / Check.py
1 ## @file
2 # This file is used to define checkpoints used by ECC tool
3 #
4 # Copyright (c) 2008 - 2018, 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
9 #
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.
12 #
13 from __future__ import absolute_import
14 import Common.LongFilePathOs as os
15 import re
16 from CommonDataClass.DataClass import *
17 import Common.DataType as DT
18 from .EccToolError import *
19 from .MetaDataParser import ParseHeaderCommentSection
20 from . import EccGlobalData
21 from . import c
22 from Common.LongFilePathSupport import OpenLongFilePath as open
23 from Common.MultipleWorkspace import MultipleWorkspace as mws
24
25 ## Check
26 #
27 # This class is to define checkpoints used by ECC tool
28 #
29 # @param object: Inherited from object class
30 #
31 class Check(object):
32 def __init__(self):
33 pass
34
35 # Check all required checkpoints
36 def Check(self):
37 self.GeneralCheck()
38 self.MetaDataFileCheck()
39 self.DoxygenCheck()
40 self.IncludeFileCheck()
41 self.PredicateExpressionCheck()
42 self.DeclAndDataTypeCheck()
43 self.FunctionLayoutCheck()
44 self.NamingConventionCheck()
45 self.SmmCommParaCheck()
46
47 def SmmCommParaCheck(self):
48 self.SmmCommParaCheckBufferType()
49
50
51 # Check if SMM communication function has correct parameter type
52 # 1. Get function calling with instance./->Communicate() interface
53 # and make sure the protocol instance is of type EFI_SMM_COMMUNICATION_PROTOCOL.
54 # 2. Find the origin of the 2nd parameter of Communicate() interface, if -
55 # a. it is a local buffer on stack
56 # report error.
57 # b. it is a global buffer, check the driver that holds the global buffer is of type DXE_RUNTIME_DRIVER
58 # report success.
59 # c. it is a buffer by AllocatePage/AllocatePool (may be wrapped by nested function calls),
60 # check the EFI_MEMORY_TYPE to be EfiRuntimeServicesCode,EfiRuntimeServicesData,
61 # EfiACPIMemoryNVS or EfiReservedMemoryType
62 # report success.
63 # d. it is a buffer located via EFI_SYSTEM_TABLE.ConfigurationTable (may be wrapped by nested function calls)
64 # report warning to indicate human code review.
65 # e. it is a buffer from other kind of pointers (may need to trace into nested function calls to locate),
66 # repeat checks in a.b.c and d.
67 def SmmCommParaCheckBufferType(self):
68 if EccGlobalData.gConfig.SmmCommParaCheckBufferType == '1' or EccGlobalData.gConfig.SmmCommParaCheckAll == '1':
69 EdkLogger.quiet("Checking SMM communication parameter type ...")
70 # Get all EFI_SMM_COMMUNICATION_PROTOCOL interface
71 CommApiList = []
72 for IdentifierTable in EccGlobalData.gIdentifierTableList:
73 SqlCommand = """select ID, Name, BelongsToFile from %s
74 where Modifier = 'EFI_SMM_COMMUNICATION_PROTOCOL*' """ % (IdentifierTable)
75 RecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
76 if RecordSet:
77 for Record in RecordSet:
78 if Record[1] not in CommApiList:
79 CommApiList.append(Record[1])
80 # For each interface, check the second parameter
81 for CommApi in CommApiList:
82 for IdentifierTable in EccGlobalData.gIdentifierTableList:
83 SqlCommand = """select ID, Name, Value, BelongsToFile, StartLine from %s
84 where Name = '%s->Communicate' and Model = %s""" \
85 % (IdentifierTable, CommApi, MODEL_IDENTIFIER_FUNCTION_CALLING)
86 RecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
87 if RecordSet:
88 # print IdentifierTable
89 for Record in RecordSet:
90 # Get the second parameter for Communicate function
91 SecondPara = Record[2].split(',')[1].strip()
92 SecondParaIndex = None
93 if SecondPara.startswith('&'):
94 SecondPara = SecondPara[1:]
95 if SecondPara.endswith(']'):
96 SecondParaIndex = SecondPara[SecondPara.find('[') + 1:-1]
97 SecondPara = SecondPara[:SecondPara.find('[')]
98 # Get the ID
99 Id = Record[0]
100 # Get the BelongsToFile
101 BelongsToFile = Record[3]
102 # Get the source file path
103 SqlCommand = """select FullPath from File where ID = %s""" % BelongsToFile
104 NewRecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
105 FullPath = NewRecordSet[0][0]
106 # Get the line no of function calling
107 StartLine = Record[4]
108 # Get the module type
109 SqlCommand = """select Value3 from INF where BelongsToFile = (select ID from File
110 where Path = (select Path from File where ID = %s) and Model = 1011)
111 and Value2 = 'MODULE_TYPE'""" % BelongsToFile
112 NewRecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
113 ModuleType = NewRecordSet[0][0] if NewRecordSet else None
114
115 # print BelongsToFile, FullPath, StartLine, ModuleType, SecondPara
116
117 Value = FindPara(FullPath, SecondPara, StartLine)
118 # Find the value of the parameter
119 if Value:
120 if 'AllocatePage' in Value \
121 or 'AllocatePool' in Value \
122 or 'AllocateRuntimePool' in Value \
123 or 'AllocateZeroPool' in Value:
124 pass
125 else:
126 if '->' in Value:
127 if not EccGlobalData.gException.IsException(
128 ERROR_SMM_COMM_PARA_CHECK_BUFFER_TYPE, Value):
129 EccGlobalData.gDb.TblReport.Insert(ERROR_SMM_COMM_PARA_CHECK_BUFFER_TYPE,
130 OtherMsg="Please review the buffer type"
131 + "is correct or not. If it is correct" +
132 " please add [%s] to exception list"
133 % Value,
134 BelongsToTable=IdentifierTable,
135 BelongsToItem=Id)
136 else:
137 if not EccGlobalData.gException.IsException(
138 ERROR_SMM_COMM_PARA_CHECK_BUFFER_TYPE, Value):
139 EccGlobalData.gDb.TblReport.Insert(ERROR_SMM_COMM_PARA_CHECK_BUFFER_TYPE,
140 OtherMsg="Please review the buffer type"
141 + "is correct or not. If it is correct" +
142 " please add [%s] to exception list"
143 % Value,
144 BelongsToTable=IdentifierTable,
145 BelongsToItem=Id)
146
147
148 # Not find the value of the parameter
149 else:
150 SqlCommand = """select ID, Modifier, Name, Value, Model, BelongsToFunction from %s
151 where Name = '%s' and StartLine < %s order by StartLine DESC""" \
152 % (IdentifierTable, SecondPara, StartLine)
153 NewRecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
154 if NewRecordSet:
155 Value = NewRecordSet[0][1]
156 if 'AllocatePage' in Value \
157 or 'AllocatePool' in Value \
158 or 'AllocateRuntimePool' in Value \
159 or 'AllocateZeroPool' in Value:
160 pass
161 else:
162 if not EccGlobalData.gException.IsException(
163 ERROR_SMM_COMM_PARA_CHECK_BUFFER_TYPE, Value):
164 EccGlobalData.gDb.TblReport.Insert(ERROR_SMM_COMM_PARA_CHECK_BUFFER_TYPE,
165 OtherMsg="Please review the buffer type"
166 + "is correct or not. If it is correct" +
167 " please add [%s] to exception list"
168 % Value,
169 BelongsToTable=IdentifierTable,
170 BelongsToItem=Id)
171 else:
172 pass
173
174 # Check UNI files
175 def UniCheck(self):
176 if EccGlobalData.gConfig.GeneralCheckUni == '1' or EccGlobalData.gConfig.GeneralCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
177 EdkLogger.quiet("Checking whether UNI file is UTF-16 ...")
178 SqlCommand = """select ID, FullPath, ExtName from File where ExtName like 'uni'"""
179 RecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
180 for Record in RecordSet:
181 File = Record[1]
182 FileIn = open(File, 'rb').read(2)
183 if FileIn != '\xff\xfe':
184 OtherMsg = "File %s is not a valid UTF-16 UNI file" % Record[1]
185 EccGlobalData.gDb.TblReport.Insert(ERROR_GENERAL_CHECK_UNI, OtherMsg=OtherMsg, BelongsToTable='File', BelongsToItem=Record[0])
186
187 # General Checking
188 def GeneralCheck(self):
189 self.GeneralCheckNonAcsii()
190 self.UniCheck()
191
192 # Check whether file has non ACSII char
193 def GeneralCheckNonAcsii(self):
194 if EccGlobalData.gConfig.GeneralCheckNonAcsii == '1' or EccGlobalData.gConfig.GeneralCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
195 EdkLogger.quiet("Checking Non-ACSII char in file ...")
196 SqlCommand = """select ID, FullPath, ExtName from File where ExtName in ('.dec', '.inf', '.dsc', 'c', 'h')"""
197 RecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
198 for Record in RecordSet:
199 if Record[2].upper() not in EccGlobalData.gConfig.BinaryExtList:
200 op = open(Record[1]).readlines()
201 IndexOfLine = 0
202 for Line in op:
203 IndexOfLine += 1
204 IndexOfChar = 0
205 for Char in Line:
206 IndexOfChar += 1
207 if ord(Char) > 126:
208 OtherMsg = "File %s has Non-ASCII char at line %s column %s" % (Record[1], IndexOfLine, IndexOfChar)
209 EccGlobalData.gDb.TblReport.Insert(ERROR_GENERAL_CHECK_NON_ACSII, OtherMsg=OtherMsg, BelongsToTable='File', BelongsToItem=Record[0])
210
211 # C Function Layout Checking
212 def FunctionLayoutCheck(self):
213 self.FunctionLayoutCheckReturnType()
214 self.FunctionLayoutCheckModifier()
215 self.FunctionLayoutCheckName()
216 self.FunctionLayoutCheckPrototype()
217 self.FunctionLayoutCheckBody()
218 self.FunctionLayoutCheckLocalVariable()
219
220 def WalkTree(self):
221 IgnoredPattern = c.GetIgnoredDirListPattern()
222 for Dirpath, Dirnames, Filenames in os.walk(EccGlobalData.gTarget):
223 for Dir in Dirnames:
224 Dirname = os.path.join(Dirpath, Dir)
225 if os.path.islink(Dirname):
226 Dirname = os.path.realpath(Dirname)
227 if os.path.isdir(Dirname):
228 # symlinks to directories are treated as directories
229 Dirnames.remove(Dir)
230 Dirnames.append(Dirname)
231 if IgnoredPattern.match(Dirpath.upper()):
232 continue
233 for f in Filenames[:]:
234 if f.lower() in EccGlobalData.gConfig.SkipFileList:
235 Filenames.remove(f)
236 yield (Dirpath, Dirnames, Filenames)
237
238 # Check whether return type exists and in the first line
239 def FunctionLayoutCheckReturnType(self):
240 if EccGlobalData.gConfig.CFunctionLayoutCheckReturnType == '1' or EccGlobalData.gConfig.CFunctionLayoutCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
241 EdkLogger.quiet("Checking function layout return type ...")
242
243 # for Dirpath, Dirnames, Filenames in self.WalkTree():
244 # for F in Filenames:
245 # if os.path.splitext(F)[1] in ('.c', '.h'):
246 # FullName = os.path.join(Dirpath, F)
247 # c.CheckFuncLayoutReturnType(FullName)
248 for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFileList:
249 c.CheckFuncLayoutReturnType(FullName)
250
251 # Check whether any optional functional modifiers exist and next to the return type
252 def FunctionLayoutCheckModifier(self):
253 if EccGlobalData.gConfig.CFunctionLayoutCheckOptionalFunctionalModifier == '1' or EccGlobalData.gConfig.CFunctionLayoutCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
254 EdkLogger.quiet("Checking function layout modifier ...")
255
256 # for Dirpath, Dirnames, Filenames in self.WalkTree():
257 # for F in Filenames:
258 # if os.path.splitext(F)[1] in ('.c', '.h'):
259 # FullName = os.path.join(Dirpath, F)
260 # c.CheckFuncLayoutModifier(FullName)
261 for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFileList:
262 c.CheckFuncLayoutModifier(FullName)
263
264 # Check whether the next line contains the function name, left justified, followed by the beginning of the parameter list
265 # Check whether the closing parenthesis is on its own line and also indented two spaces
266 def FunctionLayoutCheckName(self):
267 if EccGlobalData.gConfig.CFunctionLayoutCheckFunctionName == '1' or EccGlobalData.gConfig.CFunctionLayoutCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
268 EdkLogger.quiet("Checking function layout function name ...")
269
270 # for Dirpath, Dirnames, Filenames in self.WalkTree():
271 # for F in Filenames:
272 # if os.path.splitext(F)[1] in ('.c', '.h'):
273 # FullName = os.path.join(Dirpath, F)
274 # c.CheckFuncLayoutName(FullName)
275 for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFileList:
276 c.CheckFuncLayoutName(FullName)
277
278 # Check whether the function prototypes in include files have the same form as function definitions
279 def FunctionLayoutCheckPrototype(self):
280 if EccGlobalData.gConfig.CFunctionLayoutCheckFunctionPrototype == '1' or EccGlobalData.gConfig.CFunctionLayoutCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
281 EdkLogger.quiet("Checking function layout function prototype ...")
282
283 # for Dirpath, Dirnames, Filenames in self.WalkTree():
284 # for F in Filenames:
285 # if os.path.splitext(F)[1] in ('.c'):
286 # FullName = os.path.join(Dirpath, F)
287 # EdkLogger.quiet("[PROTOTYPE]" + FullName)
288 # c.CheckFuncLayoutPrototype(FullName)
289 for FullName in EccGlobalData.gCFileList:
290 EdkLogger.quiet("[PROTOTYPE]" + FullName)
291 c.CheckFuncLayoutPrototype(FullName)
292
293 # Check whether the body of a function is contained by open and close braces that must be in the first column
294 def FunctionLayoutCheckBody(self):
295 if EccGlobalData.gConfig.CFunctionLayoutCheckFunctionBody == '1' or EccGlobalData.gConfig.CFunctionLayoutCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
296 EdkLogger.quiet("Checking function layout function body ...")
297
298 # for Dirpath, Dirnames, Filenames in self.WalkTree():
299 # for F in Filenames:
300 # if os.path.splitext(F)[1] in ('.c'):
301 # FullName = os.path.join(Dirpath, F)
302 # c.CheckFuncLayoutBody(FullName)
303 for FullName in EccGlobalData.gCFileList:
304 c.CheckFuncLayoutBody(FullName)
305
306 # Check whether the data declarations is the first code in a module.
307 # self.CFunctionLayoutCheckDataDeclaration = 1
308 # Check whether no initialization of a variable as part of its declaration
309 def FunctionLayoutCheckLocalVariable(self):
310 if EccGlobalData.gConfig.CFunctionLayoutCheckNoInitOfVariable == '1' or EccGlobalData.gConfig.CFunctionLayoutCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
311 EdkLogger.quiet("Checking function layout local variables ...")
312
313 # for Dirpath, Dirnames, Filenames in self.WalkTree():
314 # for F in Filenames:
315 # if os.path.splitext(F)[1] in ('.c'):
316 # FullName = os.path.join(Dirpath, F)
317 # c.CheckFuncLayoutLocalVariable(FullName)
318
319 for FullName in EccGlobalData.gCFileList:
320 c.CheckFuncLayoutLocalVariable(FullName)
321
322 # Check whether no use of STATIC for functions
323 # self.CFunctionLayoutCheckNoStatic = 1
324
325 # Declarations and Data Types Checking
326 def DeclAndDataTypeCheck(self):
327 self.DeclCheckNoUseCType()
328 self.DeclCheckInOutModifier()
329 self.DeclCheckEFIAPIModifier()
330 self.DeclCheckEnumeratedType()
331 self.DeclCheckStructureDeclaration()
332 self.DeclCheckSameStructure()
333 self.DeclCheckUnionType()
334
335
336 # Check whether no use of int, unsigned, char, void, static, long in any .c, .h or .asl files.
337 def DeclCheckNoUseCType(self):
338 if EccGlobalData.gConfig.DeclarationDataTypeCheckNoUseCType == '1' or EccGlobalData.gConfig.DeclarationDataTypeCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
339 EdkLogger.quiet("Checking Declaration No use C type ...")
340
341 # for Dirpath, Dirnames, Filenames in self.WalkTree():
342 # for F in Filenames:
343 # if os.path.splitext(F)[1] in ('.h', '.c'):
344 # FullName = os.path.join(Dirpath, F)
345 # c.CheckDeclNoUseCType(FullName)
346 for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFileList:
347 c.CheckDeclNoUseCType(FullName)
348
349 # Check whether the modifiers IN, OUT, OPTIONAL, and UNALIGNED are used only to qualify arguments to a function and should not appear in a data type declaration
350 def DeclCheckInOutModifier(self):
351 if EccGlobalData.gConfig.DeclarationDataTypeCheckInOutModifier == '1' or EccGlobalData.gConfig.DeclarationDataTypeCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
352 EdkLogger.quiet("Checking Declaration argument modifier ...")
353
354 # for Dirpath, Dirnames, Filenames in self.WalkTree():
355 # for F in Filenames:
356 # if os.path.splitext(F)[1] in ('.h', '.c'):
357 # FullName = os.path.join(Dirpath, F)
358 # c.CheckDeclArgModifier(FullName)
359 for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFileList:
360 c.CheckDeclArgModifier(FullName)
361
362 # Check whether the EFIAPI modifier should be used at the entry of drivers, events, and member functions of protocols
363 def DeclCheckEFIAPIModifier(self):
364 if EccGlobalData.gConfig.DeclarationDataTypeCheckEFIAPIModifier == '1' or EccGlobalData.gConfig.DeclarationDataTypeCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
365 pass
366
367 # Check whether Enumerated Type has a 'typedef' and the name is capital
368 def DeclCheckEnumeratedType(self):
369 if EccGlobalData.gConfig.DeclarationDataTypeCheckEnumeratedType == '1' or EccGlobalData.gConfig.DeclarationDataTypeCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
370 EdkLogger.quiet("Checking Declaration enum typedef ...")
371
372 # for Dirpath, Dirnames, Filenames in self.WalkTree():
373 # for F in Filenames:
374 # if os.path.splitext(F)[1] in ('.h', '.c'):
375 # FullName = os.path.join(Dirpath, F)
376 # EdkLogger.quiet("[ENUM]" + FullName)
377 # c.CheckDeclEnumTypedef(FullName)
378 for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFileList:
379 EdkLogger.quiet("[ENUM]" + FullName)
380 c.CheckDeclEnumTypedef(FullName)
381
382 # Check whether Structure Type has a 'typedef' and the name is capital
383 def DeclCheckStructureDeclaration(self):
384 if EccGlobalData.gConfig.DeclarationDataTypeCheckStructureDeclaration == '1' or EccGlobalData.gConfig.DeclarationDataTypeCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
385 EdkLogger.quiet("Checking Declaration struct typedef ...")
386
387 # for Dirpath, Dirnames, Filenames in self.WalkTree():
388 # for F in Filenames:
389 # if os.path.splitext(F)[1] in ('.h', '.c'):
390 # FullName = os.path.join(Dirpath, F)
391 # EdkLogger.quiet("[STRUCT]" + FullName)
392 # c.CheckDeclStructTypedef(FullName)
393 for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFileList:
394 EdkLogger.quiet("[STRUCT]" + FullName)
395 c.CheckDeclStructTypedef(FullName)
396
397 # Check whether having same Structure
398 def DeclCheckSameStructure(self):
399 if EccGlobalData.gConfig.DeclarationDataTypeCheckSameStructure == '1' or EccGlobalData.gConfig.DeclarationDataTypeCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
400 EdkLogger.quiet("Checking same struct ...")
401 AllStructure = {}
402 for IdentifierTable in EccGlobalData.gIdentifierTableList:
403 SqlCommand = """select ID, Name, BelongsToFile from %s where Model = %s""" % (IdentifierTable, MODEL_IDENTIFIER_STRUCTURE)
404 RecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
405 for Record in RecordSet:
406 if Record[1] != '':
407 if Record[1] not in AllStructure.keys():
408 AllStructure[Record[1]] = Record[2]
409 else:
410 ID = AllStructure[Record[1]]
411 SqlCommand = """select FullPath from File where ID = %s """ % ID
412 NewRecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
413 OtherMsg = "The structure name '%s' is duplicate" % Record[1]
414 if NewRecordSet != []:
415 OtherMsg = "The structure name [%s] is duplicate with the one defined in %s, maybe struct NOT typedefed or the typedef new type NOT used to qualify variables" % (Record[1], NewRecordSet[0][0])
416 if not EccGlobalData.gException.IsException(ERROR_DECLARATION_DATA_TYPE_CHECK_SAME_STRUCTURE, Record[1]):
417 EccGlobalData.gDb.TblReport.Insert(ERROR_DECLARATION_DATA_TYPE_CHECK_SAME_STRUCTURE, OtherMsg=OtherMsg, BelongsToTable=IdentifierTable, BelongsToItem=Record[0])
418
419 # Check whether Union Type has a 'typedef' and the name is capital
420 def DeclCheckUnionType(self):
421 if EccGlobalData.gConfig.DeclarationDataTypeCheckUnionType == '1' or EccGlobalData.gConfig.DeclarationDataTypeCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
422 EdkLogger.quiet("Checking Declaration union typedef ...")
423
424 # for Dirpath, Dirnames, Filenames in self.WalkTree():
425 # for F in Filenames:
426 # if os.path.splitext(F)[1] in ('.h', '.c'):
427 # FullName = os.path.join(Dirpath, F)
428 # EdkLogger.quiet("[UNION]" + FullName)
429 # c.CheckDeclUnionTypedef(FullName)
430 for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFileList:
431 EdkLogger.quiet("[UNION]" + FullName)
432 c.CheckDeclUnionTypedef(FullName)
433
434 # Predicate Expression Checking
435 def PredicateExpressionCheck(self):
436 self.PredicateExpressionCheckBooleanValue()
437 self.PredicateExpressionCheckNonBooleanOperator()
438 self.PredicateExpressionCheckComparisonNullType()
439
440 # Check whether Boolean values, variable type BOOLEAN not use explicit comparisons to TRUE or FALSE
441 def PredicateExpressionCheckBooleanValue(self):
442 if EccGlobalData.gConfig.PredicateExpressionCheckBooleanValue == '1' or EccGlobalData.gConfig.PredicateExpressionCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
443 EdkLogger.quiet("Checking predicate expression Boolean value ...")
444
445 # for Dirpath, Dirnames, Filenames in self.WalkTree():
446 # for F in Filenames:
447 # if os.path.splitext(F)[1] in ('.c'):
448 # FullName = os.path.join(Dirpath, F)
449 # EdkLogger.quiet("[BOOLEAN]" + FullName)
450 # c.CheckBooleanValueComparison(FullName)
451 for FullName in EccGlobalData.gCFileList:
452 EdkLogger.quiet("[BOOLEAN]" + FullName)
453 c.CheckBooleanValueComparison(FullName)
454
455 # Check whether Non-Boolean comparisons use a compare operator (==, !=, >, < >=, <=).
456 def PredicateExpressionCheckNonBooleanOperator(self):
457 if EccGlobalData.gConfig.PredicateExpressionCheckNonBooleanOperator == '1' or EccGlobalData.gConfig.PredicateExpressionCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
458 EdkLogger.quiet("Checking predicate expression Non-Boolean variable...")
459
460 # for Dirpath, Dirnames, Filenames in self.WalkTree():
461 # for F in Filenames:
462 # if os.path.splitext(F)[1] in ('.c'):
463 # FullName = os.path.join(Dirpath, F)
464 # EdkLogger.quiet("[NON-BOOLEAN]" + FullName)
465 # c.CheckNonBooleanValueComparison(FullName)
466 for FullName in EccGlobalData.gCFileList:
467 EdkLogger.quiet("[NON-BOOLEAN]" + FullName)
468 c.CheckNonBooleanValueComparison(FullName)
469
470 # Check whether a comparison of any pointer to zero must be done via the NULL type
471 def PredicateExpressionCheckComparisonNullType(self):
472 if EccGlobalData.gConfig.PredicateExpressionCheckComparisonNullType == '1' or EccGlobalData.gConfig.PredicateExpressionCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
473 EdkLogger.quiet("Checking predicate expression NULL pointer ...")
474
475 # for Dirpath, Dirnames, Filenames in self.WalkTree():
476 # for F in Filenames:
477 # if os.path.splitext(F)[1] in ('.c'):
478 # FullName = os.path.join(Dirpath, F)
479 # EdkLogger.quiet("[POINTER]" + FullName)
480 # c.CheckPointerNullComparison(FullName)
481 for FullName in EccGlobalData.gCFileList:
482 EdkLogger.quiet("[POINTER]" + FullName)
483 c.CheckPointerNullComparison(FullName)
484
485 # Include file checking
486 def IncludeFileCheck(self):
487 self.IncludeFileCheckIfndef()
488 self.IncludeFileCheckData()
489 self.IncludeFileCheckSameName()
490
491 # Check whether having include files with same name
492 def IncludeFileCheckSameName(self):
493 if EccGlobalData.gConfig.IncludeFileCheckSameName == '1' or EccGlobalData.gConfig.IncludeFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
494 EdkLogger.quiet("Checking same header file name ...")
495 SqlCommand = """select ID, FullPath from File
496 where Model = 1002 order by Name """
497 RecordDict = {}
498 RecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
499 for Record in RecordSet:
500 List = Record[1].replace('/', '\\').split('\\')
501 if len(List) >= 2:
502 Key = List[-2] + '\\' + List[-1]
503 else:
504 Key = List[0]
505 if Key not in RecordDict:
506 RecordDict[Key] = [Record]
507 else:
508 RecordDict[Key].append(Record)
509
510 for Key in RecordDict:
511 if len(RecordDict[Key]) > 1:
512 for Item in RecordDict[Key]:
513 Path = mws.relpath(Item[1], EccGlobalData.gWorkspace)
514 if not EccGlobalData.gException.IsException(ERROR_INCLUDE_FILE_CHECK_NAME, Path):
515 EccGlobalData.gDb.TblReport.Insert(ERROR_INCLUDE_FILE_CHECK_NAME, OtherMsg="The file name for [%s] is duplicate" % Path, BelongsToTable='File', BelongsToItem=Item[0])
516
517 # Check whether all include file contents is guarded by a #ifndef statement.
518 def IncludeFileCheckIfndef(self):
519 if EccGlobalData.gConfig.IncludeFileCheckIfndefStatement == '1' or EccGlobalData.gConfig.IncludeFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
520 EdkLogger.quiet("Checking header file ifndef ...")
521
522 # for Dirpath, Dirnames, Filenames in self.WalkTree():
523 # for F in Filenames:
524 # if os.path.splitext(F)[1] in ('.h'):
525 # FullName = os.path.join(Dirpath, F)
526 # MsgList = c.CheckHeaderFileIfndef(FullName)
527 for FullName in EccGlobalData.gHFileList:
528 MsgList = c.CheckHeaderFileIfndef(FullName)
529
530 # Check whether include files NOT contain code or define data variables
531 def IncludeFileCheckData(self):
532 if EccGlobalData.gConfig.IncludeFileCheckData == '1' or EccGlobalData.gConfig.IncludeFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
533 EdkLogger.quiet("Checking header file data ...")
534
535 # for Dirpath, Dirnames, Filenames in self.WalkTree():
536 # for F in Filenames:
537 # if os.path.splitext(F)[1] in ('.h'):
538 # FullName = os.path.join(Dirpath, F)
539 # MsgList = c.CheckHeaderFileData(FullName)
540 for FullName in EccGlobalData.gHFileList:
541 MsgList = c.CheckHeaderFileData(FullName)
542
543 # Doxygen document checking
544 def DoxygenCheck(self):
545 self.DoxygenCheckFileHeader()
546 self.DoxygenCheckFunctionHeader()
547 self.DoxygenCheckCommentDescription()
548 self.DoxygenCheckCommentFormat()
549 self.DoxygenCheckCommand()
550
551 # Check whether the file headers are followed Doxygen special documentation blocks in section 2.3.5
552 def DoxygenCheckFileHeader(self):
553 if EccGlobalData.gConfig.DoxygenCheckFileHeader == '1' or EccGlobalData.gConfig.DoxygenCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
554 EdkLogger.quiet("Checking Doxygen file header ...")
555
556 for Dirpath, Dirnames, Filenames in self.WalkTree():
557 for F in Filenames:
558 Ext = os.path.splitext(F)[1]
559 if Ext in ('.h', '.c'):
560 FullName = os.path.join(Dirpath, F)
561 MsgList = c.CheckFileHeaderDoxygenComments(FullName)
562 elif Ext in ('.inf', '.dec', '.dsc', '.fdf'):
563 FullName = os.path.join(Dirpath, F)
564 op = open(FullName).readlines()
565 FileLinesList = op
566 LineNo = 0
567 CurrentSection = MODEL_UNKNOWN
568 HeaderSectionLines = []
569 HeaderCommentStart = False
570 HeaderCommentEnd = False
571
572 for Line in FileLinesList:
573 LineNo = LineNo + 1
574 Line = Line.strip()
575 if (LineNo < len(FileLinesList) - 1):
576 NextLine = FileLinesList[LineNo].strip()
577
578 #
579 # blank line
580 #
581 if (Line == '' or not Line) and LineNo == len(FileLinesList):
582 LastSectionFalg = True
583
584 #
585 # check whether file header comment section started
586 #
587 if Line.startswith('#') and \
588 (Line.find('@file') > -1) and \
589 not HeaderCommentStart:
590 if CurrentSection != MODEL_UNKNOWN:
591 SqlStatement = """ select ID from File where FullPath like '%s'""" % FullName
592 ResultSet = EccGlobalData.gDb.TblFile.Exec(SqlStatement)
593 for Result in ResultSet:
594 Msg = 'INF/DEC/DSC/FDF file header comment should begin with ""## @file"" or ""# @file""at the very top file'
595 EccGlobalData.gDb.TblReport.Insert(ERROR_DOXYGEN_CHECK_FILE_HEADER, Msg, "File", Result[0])
596
597 else:
598 CurrentSection = MODEL_IDENTIFIER_FILE_HEADER
599 #
600 # Append the first line to section lines.
601 #
602 HeaderSectionLines.append((Line, LineNo))
603 HeaderCommentStart = True
604 continue
605
606 #
607 # Collect Header content.
608 #
609 if (Line.startswith('#') and CurrentSection == MODEL_IDENTIFIER_FILE_HEADER) and\
610 HeaderCommentStart and not Line.startswith('##') and not\
611 HeaderCommentEnd and NextLine != '':
612 HeaderSectionLines.append((Line, LineNo))
613 continue
614 #
615 # Header content end
616 #
617 if (Line.startswith('##') or not Line.strip().startswith("#")) and HeaderCommentStart \
618 and not HeaderCommentEnd:
619 if Line.startswith('##'):
620 HeaderCommentEnd = True
621 HeaderSectionLines.append((Line, LineNo))
622 ParseHeaderCommentSection(HeaderSectionLines, FullName)
623 break
624 if HeaderCommentStart == False:
625 SqlStatement = """ select ID from File where FullPath like '%s'""" % FullName
626 ResultSet = EccGlobalData.gDb.TblFile.Exec(SqlStatement)
627 for Result in ResultSet:
628 Msg = 'INF/DEC/DSC/FDF file header comment should begin with ""## @file"" or ""# @file"" at the very top file'
629 EccGlobalData.gDb.TblReport.Insert(ERROR_DOXYGEN_CHECK_FILE_HEADER, Msg, "File", Result[0])
630 if HeaderCommentEnd == False:
631 SqlStatement = """ select ID from File where FullPath like '%s'""" % FullName
632 ResultSet = EccGlobalData.gDb.TblFile.Exec(SqlStatement)
633 for Result in ResultSet:
634 Msg = 'INF/DEC/DSC/FDF file header comment should end with ""##"" at the end of file header comment block'
635 # Check whether File header Comment End with '##'
636 if EccGlobalData.gConfig.HeaderCheckFileCommentEnd == '1' or EccGlobalData.gConfig.HeaderCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
637 EccGlobalData.gDb.TblReport.Insert(ERROR_DOXYGEN_CHECK_FILE_HEADER, Msg, "File", Result[0])
638
639
640
641 # Check whether the function headers are followed Doxygen special documentation blocks in section 2.3.5
642 def DoxygenCheckFunctionHeader(self):
643 if EccGlobalData.gConfig.DoxygenCheckFunctionHeader == '1' or EccGlobalData.gConfig.DoxygenCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
644 EdkLogger.quiet("Checking Doxygen function header ...")
645
646 # for Dirpath, Dirnames, Filenames in self.WalkTree():
647 # for F in Filenames:
648 # if os.path.splitext(F)[1] in ('.h', '.c'):
649 # FullName = os.path.join(Dirpath, F)
650 # MsgList = c.CheckFuncHeaderDoxygenComments(FullName)
651 for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFileList:
652 MsgList = c.CheckFuncHeaderDoxygenComments(FullName)
653
654
655 # Check whether the first line of text in a comment block is a brief description of the element being documented.
656 # The brief description must end with a period.
657 def DoxygenCheckCommentDescription(self):
658 if EccGlobalData.gConfig.DoxygenCheckCommentDescription == '1' or EccGlobalData.gConfig.DoxygenCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
659 pass
660
661 # Check whether comment lines with '///< ... text ...' format, if it is used, it should be after the code section.
662 def DoxygenCheckCommentFormat(self):
663 if EccGlobalData.gConfig.DoxygenCheckCommentFormat == '1' or EccGlobalData.gConfig.DoxygenCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
664 EdkLogger.quiet("Checking Doxygen comment ///< ...")
665
666 # for Dirpath, Dirnames, Filenames in self.WalkTree():
667 # for F in Filenames:
668 # if os.path.splitext(F)[1] in ('.h', '.c'):
669 # FullName = os.path.join(Dirpath, F)
670 # MsgList = c.CheckDoxygenTripleForwardSlash(FullName)
671 for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFileList:
672 MsgList = c.CheckDoxygenTripleForwardSlash(FullName)
673
674 # Check whether only Doxygen commands allowed to mark the code are @bug and @todo.
675 def DoxygenCheckCommand(self):
676 if EccGlobalData.gConfig.DoxygenCheckCommand == '1' or EccGlobalData.gConfig.DoxygenCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
677 EdkLogger.quiet("Checking Doxygen command ...")
678
679 # for Dirpath, Dirnames, Filenames in self.WalkTree():
680 # for F in Filenames:
681 # if os.path.splitext(F)[1] in ('.h', '.c'):
682 # FullName = os.path.join(Dirpath, F)
683 # MsgList = c.CheckDoxygenCommand(FullName)
684 for FullName in EccGlobalData.gCFileList + EccGlobalData.gHFileList:
685 MsgList = c.CheckDoxygenCommand(FullName)
686
687 # Meta-Data File Processing Checking
688 def MetaDataFileCheck(self):
689 self.MetaDataFileCheckPathName()
690 self.MetaDataFileCheckGenerateFileList()
691 self.MetaDataFileCheckLibraryInstance()
692 self.MetaDataFileCheckLibraryInstanceDependent()
693 self.MetaDataFileCheckLibraryInstanceOrder()
694 self.MetaDataFileCheckLibraryNoUse()
695 self.MetaDataFileCheckLibraryDefinedInDec()
696 self.MetaDataFileCheckBinaryInfInFdf()
697 self.MetaDataFileCheckPcdDuplicate()
698 self.MetaDataFileCheckPcdFlash()
699 self.MetaDataFileCheckPcdNoUse()
700 self.MetaDataFileCheckGuidDuplicate()
701 self.MetaDataFileCheckModuleFileNoUse()
702 self.MetaDataFileCheckPcdType()
703 self.MetaDataFileCheckModuleFileGuidDuplication()
704 self.MetaDataFileCheckModuleFileGuidFormat()
705 self.MetaDataFileCheckModuleFileProtocolFormat()
706 self.MetaDataFileCheckModuleFilePpiFormat()
707 self.MetaDataFileCheckModuleFilePcdFormat()
708
709 # Check whether each file defined in meta-data exists
710 def MetaDataFileCheckPathName(self):
711 if EccGlobalData.gConfig.MetaDataFileCheckPathName == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
712 # This item is covered when parsing Inf/Dec/Dsc files
713 pass
714
715 # Generate a list for all files defined in meta-data files
716 def MetaDataFileCheckGenerateFileList(self):
717 if EccGlobalData.gConfig.MetaDataFileCheckGenerateFileList == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
718 # This item is covered when parsing Inf/Dec/Dsc files
719 pass
720
721 # Check whether all Library Instances defined for a given module (or dependent library instance) match the module's type.
722 # Each Library Instance must specify the Supported Module Types in its Inf file,
723 # and any module specifying the library instance must be one of the supported types.
724 def MetaDataFileCheckLibraryInstance(self):
725 if EccGlobalData.gConfig.MetaDataFileCheckLibraryInstance == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
726 EdkLogger.quiet("Checking for library instance type issue ...")
727 SqlCommand = """select A.ID, A.Value3, B.Value3 from Inf as A left join Inf as B
728 where A.Value2 = 'LIBRARY_CLASS' and A.Model = %s
729 and B.Value2 = 'MODULE_TYPE' and B.Model = %s and A.BelongsToFile = B.BelongsToFile
730 group by A.BelongsToFile""" % (MODEL_META_DATA_HEADER, MODEL_META_DATA_HEADER)
731 RecordSet = EccGlobalData.gDb.TblInf.Exec(SqlCommand)
732 LibraryClasses = {}
733 for Record in RecordSet:
734 List = Record[1].split('|', 1)
735 SupModType = []
736 if len(List) == 1:
737 SupModType = DT.SUP_MODULE_LIST_STRING.split(DT.TAB_VALUE_SPLIT)
738 elif len(List) == 2:
739 SupModType = List[1].split()
740
741 if List[0] not in LibraryClasses:
742 LibraryClasses[List[0]] = SupModType
743 else:
744 for Item in SupModType:
745 if Item not in LibraryClasses[List[0]]:
746 LibraryClasses[List[0]].append(Item)
747
748 if Record[2] != DT.SUP_MODULE_BASE and Record[2] not in SupModType:
749 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_LIBRARY_INSTANCE_2, OtherMsg="The Library Class '%s' does not specify its supported module types" % (List[0]), BelongsToTable='Inf', BelongsToItem=Record[0])
750
751 SqlCommand = """select A.ID, A.Value1, B.Value3 from Inf as A left join Inf as B
752 where A.Model = %s and B.Value2 = '%s' and B.Model = %s
753 and B.BelongsToFile = A.BelongsToFile""" \
754 % (MODEL_EFI_LIBRARY_CLASS, 'MODULE_TYPE', MODEL_META_DATA_HEADER)
755 RecordSet = EccGlobalData.gDb.TblInf.Exec(SqlCommand)
756 # Merge all LibraryClasses' supmodlist
757 RecordDict = {}
758 for Record in RecordSet:
759 if Record[1] not in RecordDict:
760 RecordDict[Record[1]] = [str(Record[2])]
761 else:
762 if Record[2] not in RecordDict[Record[1]]:
763 RecordDict[Record[1]].append(Record[2])
764
765 for Record in RecordSet:
766 if Record[1] in LibraryClasses:
767 if Record[2] not in LibraryClasses[Record[1]] and DT.SUP_MODULE_BASE not in RecordDict[Record[1]]:
768 if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_LIBRARY_INSTANCE_1, Record[1]):
769 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_LIBRARY_INSTANCE_1, OtherMsg="The type of Library Class [%s] defined in Inf file does not match the type of the module" % (Record[1]), BelongsToTable='Inf', BelongsToItem=Record[0])
770 else:
771 if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_LIBRARY_INSTANCE_1, Record[1]):
772 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_LIBRARY_INSTANCE_1, OtherMsg="The type of Library Class [%s] defined in Inf file does not match the type of the module" % (Record[1]), BelongsToTable='Inf', BelongsToItem=Record[0])
773
774 # Check whether a Library Instance has been defined for all dependent library classes
775 def MetaDataFileCheckLibraryInstanceDependent(self):
776 if EccGlobalData.gConfig.MetaDataFileCheckLibraryInstanceDependent == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
777 EdkLogger.quiet("Checking for library instance dependent issue ...")
778 SqlCommand = """select ID, Value1, Value2 from Dsc where Model = %s""" % MODEL_EFI_LIBRARY_CLASS
779 LibraryClasses = EccGlobalData.gDb.TblDsc.Exec(SqlCommand)
780 for LibraryClass in LibraryClasses:
781 if LibraryClass[1].upper() == 'NULL' or LibraryClass[1].startswith('!ifdef') or LibraryClass[1].startswith('!ifndef') or LibraryClass[1].endswith('!endif'):
782 continue
783 else:
784 LibraryIns = os.path.normpath(mws.join(EccGlobalData.gWorkspace, LibraryClass[2]))
785 SkipDirString = '|'.join(EccGlobalData.gConfig.SkipDirList)
786 p = re.compile(r'.*[\\/](?:%s^\S)[\\/]?.*' % SkipDirString)
787 if p.match(os.path.split(LibraryIns)[0].upper()):
788 continue
789 SqlCommand = """select Value3 from Inf where BelongsToFile =
790 (select ID from File where lower(FullPath) = lower('%s'))
791 and Value2 = '%s'""" % (LibraryIns, DT.PLATFORM_COMPONENT_TYPE_LIBRARY_CLASS)
792 RecordSet = EccGlobalData.gDb.TblInf.Exec(SqlCommand)
793 IsFound = False
794 for Record in RecordSet:
795 LibName = Record[0].split('|', 1)[0]
796 if LibraryClass[1] == LibName:
797 IsFound = True
798 if not IsFound:
799 if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_LIBRARY_INSTANCE_DEPENDENT, LibraryClass[1]):
800 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_LIBRARY_INSTANCE_DEPENDENT, OtherMsg="The Library Class [%s] is not specified in '%s'" % (LibraryClass[1], LibraryClass[2]), BelongsToTable='Dsc', BelongsToItem=LibraryClass[0])
801
802 # Check whether the Library Instances specified by the LibraryClasses sections are listed in order of dependencies
803 def MetaDataFileCheckLibraryInstanceOrder(self):
804 if EccGlobalData.gConfig.MetaDataFileCheckLibraryInstanceOrder == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
805 # This checkpoint is not necessary for Ecc check
806 pass
807
808 # Check whether the unnecessary inclusion of library classes in the Inf file
809 # Check whether the unnecessary duplication of library classe names in the DSC file
810 def MetaDataFileCheckLibraryNoUse(self):
811 if EccGlobalData.gConfig.MetaDataFileCheckLibraryNoUse == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
812 EdkLogger.quiet("Checking for library instance not used ...")
813 SqlCommand = """select ID, Value1 from Inf as A where A.Model = %s and A.Value1 not in (select B.Value1 from Dsc as B where Model = %s)""" % (MODEL_EFI_LIBRARY_CLASS, MODEL_EFI_LIBRARY_CLASS)
814 RecordSet = EccGlobalData.gDb.TblInf.Exec(SqlCommand)
815 for Record in RecordSet:
816 if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_LIBRARY_NO_USE, Record[1]):
817 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_LIBRARY_NO_USE, OtherMsg="The Library Class [%s] is not used in any platform" % (Record[1]), BelongsToTable='Inf', BelongsToItem=Record[0])
818 SqlCommand = """
819 select A.ID, A.Value1, A.BelongsToFile, A.StartLine, B.StartLine from Dsc as A left join Dsc as B
820 where A.Model = %s and B.Model = %s and A.Scope1 = B.Scope1 and A.Scope2 = B.Scope2 and A.ID != B.ID
821 and A.Value1 = B.Value1 and A.Value2 != B.Value2 and A.BelongsToItem = -1 and B.BelongsToItem = -1 and A.StartLine != B.StartLine and B.BelongsToFile = A.BelongsToFile""" \
822 % (MODEL_EFI_LIBRARY_CLASS, MODEL_EFI_LIBRARY_CLASS)
823 RecordSet = EccGlobalData.gDb.TblDsc.Exec(SqlCommand)
824 for Record in RecordSet:
825 if Record[3] and Record[4] and Record[3] != Record[4] and Record[1] != 'NULL':
826 SqlCommand = """select FullPath from File where ID = %s""" % (Record[2])
827 FilePathList = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
828 for FilePath in FilePathList:
829 if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_LIBRARY_NAME_DUPLICATE, Record[1]):
830 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_LIBRARY_NAME_DUPLICATE, OtherMsg="The Library Class [%s] is duplicated in '%s' line %s and line %s." % (Record[1], FilePath, Record[3], Record[4]), BelongsToTable='Dsc', BelongsToItem=Record[0])
831
832 # Check the header file in Include\Library directory whether be defined in the package DEC file.
833 def MetaDataFileCheckLibraryDefinedInDec(self):
834 if EccGlobalData.gConfig.MetaDataFileCheckLibraryDefinedInDec == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
835 EdkLogger.quiet("Checking for library instance whether be defined in the package dec file ...")
836 SqlCommand = """
837 select A.Value1, A.StartLine, A.ID, B.Value1 from Inf as A left join Dec as B
838 on A.Model = B.Model and A.Value1 = B.Value1 where A.Model=%s
839 """ % MODEL_EFI_LIBRARY_CLASS
840 RecordSet = EccGlobalData.gDb.TblDsc.Exec(SqlCommand)
841 for Record in RecordSet:
842 LibraryInInf, Line, ID, LibraryDec = Record
843 if not LibraryDec:
844 if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_LIBRARY_NOT_DEFINED, LibraryInInf):
845 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_LIBRARY_NOT_DEFINED, \
846 OtherMsg="The Library Class [%s] in %s line is not defined in the associated package file." % (LibraryInInf, Line),
847 BelongsToTable='Inf', BelongsToItem=ID)
848
849 # Check whether an Inf file is specified in the FDF file, but not in the Dsc file, then the Inf file must be for a Binary module only
850 def MetaDataFileCheckBinaryInfInFdf(self):
851 if EccGlobalData.gConfig.MetaDataFileCheckBinaryInfInFdf == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
852 EdkLogger.quiet("Checking for non-binary modules defined in FDF files ...")
853 SqlCommand = """select A.ID, A.Value1 from Fdf as A
854 where A.Model = %s
855 and A.Enabled > -1
856 and A.Value1 not in
857 (select B.Value1 from Dsc as B
858 where B.Model = %s
859 and B.Enabled > -1)""" % (MODEL_META_DATA_COMPONENT, MODEL_META_DATA_COMPONENT)
860 RecordSet = EccGlobalData.gDb.TblFdf.Exec(SqlCommand)
861 for Record in RecordSet:
862 FdfID = Record[0]
863 FilePath = Record[1]
864 FilePath = os.path.normpath(mws.join(EccGlobalData.gWorkspace, FilePath))
865 SqlCommand = """select ID from Inf where Model = %s and BelongsToFile = (select ID from File where FullPath like '%s')
866 """ % (MODEL_EFI_SOURCE_FILE, FilePath)
867 NewRecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
868 if NewRecordSet != []:
869 if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_BINARY_INF_IN_FDF, FilePath):
870 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_BINARY_INF_IN_FDF, OtherMsg="File [%s] defined in FDF file and not in DSC file must be a binary module" % (FilePath), BelongsToTable='Fdf', BelongsToItem=FdfID)
871
872 # Check whether a PCD is set in a Dsc file or the FDF file, but not in both.
873 def MetaDataFileCheckPcdDuplicate(self):
874 if EccGlobalData.gConfig.MetaDataFileCheckPcdDuplicate == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
875 EdkLogger.quiet("Checking for duplicate PCDs defined in both DSC and FDF files ...")
876 SqlCommand = """
877 select A.ID, A.Value1, A.Value2, A.BelongsToFile, B.ID, B.Value1, B.Value2, B.BelongsToFile from Dsc as A, Fdf as B
878 where A.Model >= %s and A.Model < %s
879 and B.Model >= %s and B.Model < %s
880 and A.Value1 = B.Value1
881 and A.Value2 = B.Value2
882 and A.Enabled > -1
883 and B.Enabled > -1
884 group by A.ID
885 """ % (MODEL_PCD, MODEL_META_DATA_HEADER, MODEL_PCD, MODEL_META_DATA_HEADER)
886 RecordSet = EccGlobalData.gDb.TblDsc.Exec(SqlCommand)
887 for Record in RecordSet:
888 SqlCommand1 = """select Name from File where ID = %s""" % Record[3]
889 SqlCommand2 = """select Name from File where ID = %s""" % Record[7]
890 DscFileName = os.path.splitext(EccGlobalData.gDb.TblDsc.Exec(SqlCommand1)[0][0])[0]
891 FdfFileName = os.path.splitext(EccGlobalData.gDb.TblDsc.Exec(SqlCommand2)[0][0])[0]
892 if DscFileName != FdfFileName:
893 continue
894 if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_PCD_DUPLICATE, Record[1] + '.' + Record[2]):
895 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_PCD_DUPLICATE, OtherMsg="The PCD [%s] is defined in both FDF file and DSC file" % (Record[1] + '.' + Record[2]), BelongsToTable='Dsc', BelongsToItem=Record[0])
896 if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_PCD_DUPLICATE, Record[5] + '.' + Record[6]):
897 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_PCD_DUPLICATE, OtherMsg="The PCD [%s] is defined in both FDF file and DSC file" % (Record[5] + '.' + Record[6]), BelongsToTable='Fdf', BelongsToItem=Record[4])
898
899 EdkLogger.quiet("Checking for duplicate PCDs defined in DEC files ...")
900 SqlCommand = """
901 select A.ID, A.Value1, A.Value2, A.Model, B.Model from Dec as A left join Dec as B
902 where A.Model >= %s and A.Model < %s
903 and B.Model >= %s and B.Model < %s
904 and A.Value1 = B.Value1
905 and A.Value2 = B.Value2
906 and A.Scope1 = B.Scope1
907 and A.ID != B.ID
908 and A.Model = B.Model
909 and A.Enabled > -1
910 and B.Enabled > -1
911 and A.BelongsToFile = B.BelongsToFile
912 group by A.ID
913 """ % (MODEL_PCD, MODEL_META_DATA_HEADER, MODEL_PCD, MODEL_META_DATA_HEADER)
914 RecordSet = EccGlobalData.gDb.TblDec.Exec(SqlCommand)
915 for Record in RecordSet:
916 RecordCat = Record[1] + '.' + Record[2]
917 if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_PCD_DUPLICATE, RecordCat):
918 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_PCD_DUPLICATE, OtherMsg="The PCD [%s] is defined duplicated in DEC file" % RecordCat, BelongsToTable='Dec', BelongsToItem=Record[0])
919
920 # Check whether PCD settings in the FDF file can only be related to flash.
921 def MetaDataFileCheckPcdFlash(self):
922 if EccGlobalData.gConfig.MetaDataFileCheckPcdFlash == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
923 EdkLogger.quiet("Checking only Flash related PCDs are used in FDF ...")
924 SqlCommand = """
925 select ID, Value1, Value2, BelongsToFile from Fdf as A
926 where A.Model >= %s and Model < %s
927 and A.Enabled > -1
928 and A.Value2 not like '%%Flash%%'
929 """ % (MODEL_PCD, MODEL_META_DATA_HEADER)
930 RecordSet = EccGlobalData.gDb.TblFdf.Exec(SqlCommand)
931 for Record in RecordSet:
932 if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_PCD_FLASH, Record[1] + '.' + Record[2]):
933 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_PCD_FLASH, OtherMsg="The PCD [%s] defined in FDF file is not related to Flash" % (Record[1] + '.' + Record[2]), BelongsToTable='Fdf', BelongsToItem=Record[0])
934
935 # Check whether PCDs used in Inf files but not specified in Dsc or FDF files
936 def MetaDataFileCheckPcdNoUse(self):
937 if EccGlobalData.gConfig.MetaDataFileCheckPcdNoUse == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
938 EdkLogger.quiet("Checking for non-specified PCDs ...")
939 SqlCommand = """
940 select ID, Value1, Value2, BelongsToFile from Inf as A
941 where A.Model >= %s and Model < %s
942 and A.Enabled > -1
943 and (A.Value1, A.Value2) not in
944 (select Value1, Value2 from Dsc as B
945 where B.Model >= %s and B.Model < %s
946 and B.Enabled > -1)
947 and (A.Value1, A.Value2) not in
948 (select Value1, Value2 from Fdf as C
949 where C.Model >= %s and C.Model < %s
950 and C.Enabled > -1)
951 """ % (MODEL_PCD, MODEL_META_DATA_HEADER, MODEL_PCD, MODEL_META_DATA_HEADER, MODEL_PCD, MODEL_META_DATA_HEADER)
952 RecordSet = EccGlobalData.gDb.TblInf.Exec(SqlCommand)
953 for Record in RecordSet:
954 if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_PCD_NO_USE, Record[1] + '.' + Record[2]):
955 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_PCD_NO_USE, OtherMsg="The PCD [%s] defined in INF file is not specified in either DSC or FDF files" % (Record[1] + '.' + Record[2]), BelongsToTable='Inf', BelongsToItem=Record[0])
956
957 # Check whether having duplicate guids defined for Guid/Protocol/Ppi
958 def MetaDataFileCheckGuidDuplicate(self):
959 if EccGlobalData.gConfig.MetaDataFileCheckGuidDuplicate == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
960 EdkLogger.quiet("Checking for duplicate GUID/PPI/PROTOCOL ...")
961 # Check Guid
962 self.CheckGuidProtocolPpi(ERROR_META_DATA_FILE_CHECK_DUPLICATE_GUID, MODEL_EFI_GUID, EccGlobalData.gDb.TblDec)
963 self.CheckGuidProtocolPpi(ERROR_META_DATA_FILE_CHECK_DUPLICATE_GUID, MODEL_EFI_GUID, EccGlobalData.gDb.TblDsc)
964 self.CheckGuidProtocolPpiValue(ERROR_META_DATA_FILE_CHECK_DUPLICATE_GUID, MODEL_EFI_GUID)
965 # Check protocol
966 self.CheckGuidProtocolPpi(ERROR_META_DATA_FILE_CHECK_DUPLICATE_PROTOCOL, MODEL_EFI_PROTOCOL, EccGlobalData.gDb.TblDec)
967 self.CheckGuidProtocolPpi(ERROR_META_DATA_FILE_CHECK_DUPLICATE_PROTOCOL, MODEL_EFI_PROTOCOL, EccGlobalData.gDb.TblDsc)
968 self.CheckGuidProtocolPpiValue(ERROR_META_DATA_FILE_CHECK_DUPLICATE_PROTOCOL, MODEL_EFI_PROTOCOL)
969 # Check ppi
970 self.CheckGuidProtocolPpi(ERROR_META_DATA_FILE_CHECK_DUPLICATE_PPI, MODEL_EFI_PPI, EccGlobalData.gDb.TblDec)
971 self.CheckGuidProtocolPpi(ERROR_META_DATA_FILE_CHECK_DUPLICATE_PPI, MODEL_EFI_PPI, EccGlobalData.gDb.TblDsc)
972 self.CheckGuidProtocolPpiValue(ERROR_META_DATA_FILE_CHECK_DUPLICATE_PPI, MODEL_EFI_PPI)
973
974 # Check whether all files under module directory are described in INF files
975 def MetaDataFileCheckModuleFileNoUse(self):
976 if EccGlobalData.gConfig.MetaDataFileCheckModuleFileNoUse == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
977 EdkLogger.quiet("Checking for no used module files ...")
978 SqlCommand = """
979 select upper(Path) from File where ID in (select BelongsToFile from Inf where BelongsToFile != -1)
980 """
981 InfPathSet = EccGlobalData.gDb.TblInf.Exec(SqlCommand)
982 InfPathList = []
983 for Item in InfPathSet:
984 if Item[0] not in InfPathList:
985 InfPathList.append(Item[0])
986 SqlCommand = """
987 select ID, Path, FullPath from File where upper(FullPath) not in
988 (select upper(A.Path) || '\\' || upper(B.Value1) from File as A, INF as B
989 where A.ID in (select BelongsToFile from INF where Model = %s group by BelongsToFile) and
990 B.BelongsToFile = A.ID and B.Model = %s)
991 and (Model = %s or Model = %s)
992 """ % (MODEL_EFI_SOURCE_FILE, MODEL_EFI_SOURCE_FILE, MODEL_FILE_C, MODEL_FILE_H)
993 RecordSet = EccGlobalData.gDb.TblInf.Exec(SqlCommand)
994 for Record in RecordSet:
995 Path = Record[1]
996 Path = Path.upper().replace('\X64', '').replace('\IA32', '').replace('\EBC', '').replace('\IPF', '').replace('\ARM', '')
997 if Path in InfPathList:
998 if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_MODULE_FILE_NO_USE, Record[2]):
999 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_MODULE_FILE_NO_USE, OtherMsg="The source file [%s] is existing in module directory but it is not described in INF file." % (Record[2]), BelongsToTable='File', BelongsToItem=Record[0])
1000
1001 # Check whether the PCD is correctly used in C function via its type
1002 def MetaDataFileCheckPcdType(self):
1003 if EccGlobalData.gConfig.MetaDataFileCheckPcdType == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
1004 EdkLogger.quiet("Checking for pcd type in c code function usage ...")
1005 SqlCommand = """
1006 select ID, Model, Value1, Value2, BelongsToFile from INF where Model > %s and Model < %s
1007 """ % (MODEL_PCD, MODEL_META_DATA_HEADER)
1008 PcdSet = EccGlobalData.gDb.TblInf.Exec(SqlCommand)
1009 for Pcd in PcdSet:
1010 Model = Pcd[1]
1011 PcdName = Pcd[2]
1012 if Pcd[3]:
1013 PcdName = Pcd[3]
1014 BelongsToFile = Pcd[4]
1015 SqlCommand = """
1016 select ID from File where FullPath in
1017 (select B.Path || '\\' || A.Value1 from INF as A, File as B where A.Model = %s and A.BelongsToFile = %s
1018 and B.ID = %s and (B.Model = %s or B.Model = %s))
1019 """ % (MODEL_EFI_SOURCE_FILE, BelongsToFile, BelongsToFile, MODEL_FILE_C, MODEL_FILE_H)
1020 TableSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
1021 for Tbl in TableSet:
1022 TblName = 'Identifier' + str(Tbl[0])
1023 SqlCommand = """
1024 select Name, ID from %s where value like '%s' and Model = %s
1025 """ % (TblName, PcdName, MODEL_IDENTIFIER_FUNCTION_CALLING)
1026 RecordSet = EccGlobalData.gDb.TblInf.Exec(SqlCommand)
1027 TblNumber = TblName.replace('Identifier', '')
1028 for Record in RecordSet:
1029 FunName = Record[0]
1030 if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_PCD_TYPE, FunName):
1031 if Model in [MODEL_PCD_FIXED_AT_BUILD] and not FunName.startswith('FixedPcdGet'):
1032 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_PCD_TYPE, OtherMsg="The pcd '%s' is defined as a FixPcd but now it is called by c function [%s]" % (PcdName, FunName), BelongsToTable=TblName, BelongsToItem=Record[1])
1033 if Model in [MODEL_PCD_FEATURE_FLAG] and (not FunName.startswith('FeaturePcdGet') and not FunName.startswith('FeaturePcdSet')):
1034 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_PCD_TYPE, OtherMsg="The pcd '%s' is defined as a FeaturePcd but now it is called by c function [%s]" % (PcdName, FunName), BelongsToTable=TblName, BelongsToItem=Record[1])
1035 if Model in [MODEL_PCD_PATCHABLE_IN_MODULE] and (not FunName.startswith('PatchablePcdGet') and not FunName.startswith('PatchablePcdSet')):
1036 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_PCD_TYPE, OtherMsg="The pcd '%s' is defined as a PatchablePcd but now it is called by c function [%s]" % (PcdName, FunName), BelongsToTable=TblName, BelongsToItem=Record[1])
1037
1038 #ERROR_META_DATA_FILE_CHECK_PCD_TYPE
1039 pass
1040
1041 # Internal worker function to get the INF workspace relative path from FileID
1042 def GetInfFilePathFromID(self, FileID):
1043 Table = EccGlobalData.gDb.TblFile
1044 SqlCommand = """select A.FullPath from %s as A where A.ID = %s""" % (Table.Table, FileID)
1045 RecordSet = Table.Exec(SqlCommand)
1046 Path = ""
1047 for Record in RecordSet:
1048 Path = mws.relpath(Record[0], EccGlobalData.gWorkspace)
1049 return Path
1050
1051 # Check whether two module INFs under one workspace has the same FILE_GUID value
1052 def MetaDataFileCheckModuleFileGuidDuplication(self):
1053 if EccGlobalData.gConfig.MetaDataFileCheckModuleFileGuidDuplication == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
1054 EdkLogger.quiet("Checking for pcd type in c code function usage ...")
1055 Table = EccGlobalData.gDb.TblInf
1056 SqlCommand = """
1057 select A.ID, A.Value3, A.BelongsToFile, B.BelongsToFile from %s as A, %s as B
1058 where A.Value2 = 'FILE_GUID' and B.Value2 = 'FILE_GUID' and
1059 A.Value3 = B.Value3 and A.ID != B.ID group by A.ID
1060 """ % (Table.Table, Table.Table)
1061 RecordSet = Table.Exec(SqlCommand)
1062 for Record in RecordSet:
1063 InfPath1 = self.GetInfFilePathFromID(Record[2])
1064 InfPath2 = self.GetInfFilePathFromID(Record[3])
1065 if InfPath1 and InfPath2:
1066 if not EccGlobalData.gException.IsException(ERROR_META_DATA_FILE_CHECK_MODULE_FILE_GUID_DUPLICATION, InfPath1):
1067 Msg = "The FILE_GUID of INF file [%s] is duplicated with that of %s" % (InfPath1, InfPath2)
1068 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_MODULE_FILE_GUID_DUPLICATION, OtherMsg=Msg, BelongsToTable=Table.Table, BelongsToItem=Record[0])
1069
1070
1071 # Check Guid Format in module INF
1072 def MetaDataFileCheckModuleFileGuidFormat(self):
1073 if EccGlobalData.gConfig.MetaDataFileCheckModuleFileGuidFormat == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
1074 EdkLogger.quiet("Check Guid Format in module INF ...")
1075 Table = EccGlobalData.gDb.TblInf
1076 SqlCommand = """
1077 select ID, Value1, Usage, BelongsToFile from %s where Model = %s group by ID
1078 """ % (Table.Table, MODEL_EFI_GUID)
1079 RecordSet = Table.Exec(SqlCommand)
1080 for Record in RecordSet:
1081 Value1 = Record[1]
1082 Value2 = Record[2]
1083 GuidCommentList = []
1084 InfPath = self.GetInfFilePathFromID(Record[3])
1085 Msg = "The GUID format of %s in INF file [%s] does not follow rules" % (Value1, InfPath)
1086 if Value2.startswith(DT.TAB_SPECIAL_COMMENT):
1087 GuidCommentList = Value2[2:].split(DT.TAB_SPECIAL_COMMENT)
1088 if GuidCommentList[0].strip().startswith(DT.TAB_INF_USAGE_UNDEFINED):
1089 continue
1090 elif len(GuidCommentList) > 1:
1091 if not GuidCommentList[0].strip().startswith((DT.TAB_INF_USAGE_PRO,
1092 DT.TAB_INF_USAGE_SOME_PRO,
1093 DT.TAB_INF_USAGE_CON,
1094 DT.TAB_INF_USAGE_SOME_CON)):
1095 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_FORMAT_GUID, OtherMsg=Msg, BelongsToTable=Table.Table, BelongsToItem=Record[0])
1096 if not (GuidCommentList[1].strip()).startswith(DT.TAB_INF_GUIDTYPE_VAR) and \
1097 not GuidCommentList[1].strip().startswith((DT.TAB_INF_GUIDTYPE_EVENT,
1098 DT.TAB_INF_GUIDTYPE_HII,
1099 DT.TAB_INF_GUIDTYPE_FILE,
1100 DT.TAB_INF_GUIDTYPE_HOB,
1101 DT.TAB_INF_GUIDTYPE_FV,
1102 DT.TAB_INF_GUIDTYPE_ST,
1103 DT.TAB_INF_GUIDTYPE_TSG,
1104 DT.TAB_INF_GUIDTYPE_GUID,
1105 DT.TAB_INF_GUIDTYPE_PROTOCOL,
1106 DT.TAB_INF_GUIDTYPE_PPI,
1107 DT.TAB_INF_USAGE_UNDEFINED)):
1108 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_FORMAT_GUID, OtherMsg=Msg, BelongsToTable=Table.Table, BelongsToItem=Record[0])
1109 else:
1110 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_FORMAT_GUID, OtherMsg=Msg, BelongsToTable=Table.Table, BelongsToItem=Record[0])
1111 else:
1112 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_FORMAT_GUID, OtherMsg=Msg, BelongsToTable=Table.Table, BelongsToItem=Record[0])
1113
1114 # Check Protocol Format in module INF
1115 def MetaDataFileCheckModuleFileProtocolFormat(self):
1116 if EccGlobalData.gConfig.MetaDataFileCheckModuleFileProtocolFormat == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
1117 EdkLogger.quiet("Check Protocol Format in module INF ...")
1118 Table = EccGlobalData.gDb.TblInf
1119 SqlCommand = """
1120 select ID, Value1, Usage, BelongsToFile from %s where Model = %s group by ID
1121 """ % (Table.Table, MODEL_EFI_PROTOCOL)
1122 RecordSet = Table.Exec(SqlCommand)
1123 for Record in RecordSet:
1124 Value1 = Record[1]
1125 Value2 = Record[2]
1126 GuidCommentList = []
1127 InfPath = self.GetInfFilePathFromID(Record[3])
1128 Msg = "The Protocol format of %s in INF file [%s] does not follow rules" % (Value1, InfPath)
1129 if Value2.startswith(DT.TAB_SPECIAL_COMMENT):
1130 GuidCommentList = Value2[2:].split(DT.TAB_SPECIAL_COMMENT)
1131 if len(GuidCommentList) >= 1:
1132 if not GuidCommentList[0].strip().startswith((DT.TAB_INF_USAGE_PRO,
1133 DT.TAB_INF_USAGE_SOME_PRO,
1134 DT.TAB_INF_USAGE_CON,
1135 DT.TAB_INF_USAGE_SOME_CON,
1136 DT.TAB_INF_USAGE_NOTIFY,
1137 DT.TAB_INF_USAGE_TO_START,
1138 DT.TAB_INF_USAGE_BY_START,
1139 DT.TAB_INF_USAGE_UNDEFINED)):
1140 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_FORMAT_PROTOCOL, OtherMsg=Msg, BelongsToTable=Table.Table, BelongsToItem=Record[0])
1141 else:
1142 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_FORMAT_PROTOCOL, OtherMsg=Msg, BelongsToTable=Table.Table, BelongsToItem=Record[0])
1143
1144
1145 # Check Ppi Format in module INF
1146 def MetaDataFileCheckModuleFilePpiFormat(self):
1147 if EccGlobalData.gConfig.MetaDataFileCheckModuleFilePpiFormat == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
1148 EdkLogger.quiet("Check Ppi Format in module INF ...")
1149 Table = EccGlobalData.gDb.TblInf
1150 SqlCommand = """
1151 select ID, Value1, Usage, BelongsToFile from %s where Model = %s group by ID
1152 """ % (Table.Table, MODEL_EFI_PPI)
1153 RecordSet = Table.Exec(SqlCommand)
1154 for Record in RecordSet:
1155 Value1 = Record[1]
1156 Value2 = Record[2]
1157 GuidCommentList = []
1158 InfPath = self.GetInfFilePathFromID(Record[3])
1159 Msg = "The Ppi format of %s in INF file [%s] does not follow rules" % (Value1, InfPath)
1160 if Value2.startswith(DT.TAB_SPECIAL_COMMENT):
1161 GuidCommentList = Value2[2:].split(DT.TAB_SPECIAL_COMMENT)
1162 if len(GuidCommentList) >= 1:
1163 if not GuidCommentList[0].strip().startswith((DT.TAB_INF_USAGE_PRO,
1164 DT.TAB_INF_USAGE_SOME_PRO,
1165 DT.TAB_INF_USAGE_CON,
1166 DT.TAB_INF_USAGE_SOME_CON,
1167 DT.TAB_INF_USAGE_NOTIFY,
1168 DT.TAB_INF_USAGE_UNDEFINED)):
1169 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_FORMAT_PPI, OtherMsg=Msg, BelongsToTable=Table.Table, BelongsToItem=Record[0])
1170 else:
1171 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_FORMAT_PPI, OtherMsg=Msg, BelongsToTable=Table.Table, BelongsToItem=Record[0])
1172
1173 # Check Pcd Format in module INF
1174 def MetaDataFileCheckModuleFilePcdFormat(self):
1175 if EccGlobalData.gConfig.MetaDataFileCheckModuleFilePcdFormat == '1' or EccGlobalData.gConfig.MetaDataFileCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
1176 EdkLogger.quiet("Check Pcd Format in module INF ...")
1177 Table = EccGlobalData.gDb.TblInf
1178 SqlCommand = """
1179 select ID, Model, Value1, Value2, Usage, BelongsToFile from %s where Model >= %s and Model < %s group by ID
1180 """ % (Table.Table, MODEL_PCD, MODEL_META_DATA_HEADER)
1181 RecordSet = Table.Exec(SqlCommand)
1182 for Record in RecordSet:
1183 Model = Record[1]
1184 PcdName = Record[2] + '.' + Record[3]
1185 Usage = Record[4]
1186 PcdCommentList = []
1187 InfPath = self.GetInfFilePathFromID(Record[5])
1188 Msg = "The Pcd format of %s in INF file [%s] does not follow rules" % (PcdName, InfPath)
1189 if Usage.startswith(DT.TAB_SPECIAL_COMMENT):
1190 PcdCommentList = Usage[2:].split(DT.TAB_SPECIAL_COMMENT)
1191 if len(PcdCommentList) >= 1:
1192 if Model in [MODEL_PCD_FIXED_AT_BUILD, MODEL_PCD_FEATURE_FLAG] \
1193 and not PcdCommentList[0].strip().startswith((DT.TAB_INF_USAGE_SOME_PRO,
1194 DT.TAB_INF_USAGE_CON,
1195 DT.TAB_INF_USAGE_UNDEFINED)):
1196 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_FORMAT_PCD, OtherMsg=Msg, BelongsToTable=Table.Table, BelongsToItem=Record[0])
1197 if Model in [MODEL_PCD_PATCHABLE_IN_MODULE, MODEL_PCD_DYNAMIC, MODEL_PCD_DYNAMIC_EX] \
1198 and not PcdCommentList[0].strip().startswith((DT.TAB_INF_USAGE_PRO,
1199 DT.TAB_INF_USAGE_SOME_PRO,
1200 DT.TAB_INF_USAGE_CON,
1201 DT.TAB_INF_USAGE_SOME_CON,
1202 DT.TAB_INF_USAGE_UNDEFINED)):
1203 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_FORMAT_PCD, OtherMsg=Msg, BelongsToTable=Table.Table, BelongsToItem=Record[0])
1204 else:
1205 EccGlobalData.gDb.TblReport.Insert(ERROR_META_DATA_FILE_CHECK_FORMAT_PCD, OtherMsg=Msg, BelongsToTable=Table.Table, BelongsToItem=Record[0])
1206
1207 # Check whether these is duplicate Guid/Ppi/Protocol name
1208 def CheckGuidProtocolPpi(self, ErrorID, Model, Table):
1209 Name = ''
1210 if Model == MODEL_EFI_GUID:
1211 Name = 'guid'
1212 if Model == MODEL_EFI_PROTOCOL:
1213 Name = 'protocol'
1214 if Model == MODEL_EFI_PPI:
1215 Name = 'ppi'
1216 SqlCommand = """
1217 select A.ID, A.Value1 from %s as A, %s as B
1218 where A.Model = %s and B.Model = %s
1219 and A.Value1 like B.Value1 and A.ID != B.ID
1220 and A.Scope1 = B.Scope1
1221 and A.Enabled > -1
1222 and B.Enabled > -1
1223 group by A.ID
1224 """ % (Table.Table, Table.Table, Model, Model)
1225 RecordSet = Table.Exec(SqlCommand)
1226 for Record in RecordSet:
1227 if not EccGlobalData.gException.IsException(ErrorID, Record[1]):
1228 EccGlobalData.gDb.TblReport.Insert(ErrorID, OtherMsg="The %s name [%s] is defined more than one time" % (Name.upper(), Record[1]), BelongsToTable=Table.Table, BelongsToItem=Record[0])
1229
1230 # Check whether these is duplicate Guid/Ppi/Protocol value
1231 def CheckGuidProtocolPpiValue(self, ErrorID, Model):
1232 Name = ''
1233 Table = EccGlobalData.gDb.TblDec
1234 if Model == MODEL_EFI_GUID:
1235 Name = 'guid'
1236 if Model == MODEL_EFI_PROTOCOL:
1237 Name = 'protocol'
1238 if Model == MODEL_EFI_PPI:
1239 Name = 'ppi'
1240 SqlCommand = """
1241 select A.ID, A.Value1, A.Value2 from %s as A, %s as B
1242 where A.Model = %s and B.Model = %s
1243 and A.Value2 like B.Value2 and A.ID != B.ID
1244 and A.Scope1 = B.Scope1 and A.Value1 != B.Value1
1245 group by A.ID
1246 """ % (Table.Table, Table.Table, Model, Model)
1247 RecordSet = Table.Exec(SqlCommand)
1248 for Record in RecordSet:
1249 if not EccGlobalData.gException.IsException(ErrorID, Record[2]):
1250 EccGlobalData.gDb.TblReport.Insert(ErrorID, OtherMsg="The %s value [%s] is used more than one time" % (Name.upper(), Record[2]), BelongsToTable=Table.Table, BelongsToItem=Record[0])
1251
1252 # Naming Convention Check
1253 def NamingConventionCheck(self):
1254 if EccGlobalData.gConfig.NamingConventionCheckDefineStatement == '1' \
1255 or EccGlobalData.gConfig.NamingConventionCheckTypedefStatement == '1' \
1256 or EccGlobalData.gConfig.NamingConventionCheckIfndefStatement == '1' \
1257 or EccGlobalData.gConfig.NamingConventionCheckVariableName == '1' \
1258 or EccGlobalData.gConfig.NamingConventionCheckSingleCharacterVariable == '1' \
1259 or EccGlobalData.gConfig.NamingConventionCheckAll == '1'\
1260 or EccGlobalData.gConfig.CheckAll == '1':
1261 for Dirpath, Dirnames, Filenames in self.WalkTree():
1262 for F in Filenames:
1263 if os.path.splitext(F)[1] in ('.h', '.c'):
1264 FullName = os.path.join(Dirpath, F)
1265 Id = c.GetTableID(FullName)
1266 if Id < 0:
1267 continue
1268 FileTable = 'Identifier' + str(Id)
1269 self.NamingConventionCheckDefineStatement(FileTable)
1270 self.NamingConventionCheckTypedefStatement(FileTable)
1271 self.NamingConventionCheckVariableName(FileTable)
1272 self.NamingConventionCheckSingleCharacterVariable(FileTable)
1273 if os.path.splitext(F)[1] in ('.h'):
1274 self.NamingConventionCheckIfndefStatement(FileTable)
1275
1276 self.NamingConventionCheckPathName()
1277 self.NamingConventionCheckFunctionName()
1278
1279 # Check whether only capital letters are used for #define declarations
1280 def NamingConventionCheckDefineStatement(self, FileTable):
1281 if EccGlobalData.gConfig.NamingConventionCheckDefineStatement == '1' or EccGlobalData.gConfig.NamingConventionCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
1282 EdkLogger.quiet("Checking naming covention of #define statement ...")
1283
1284 SqlCommand = """select ID, Value from %s where Model = %s""" % (FileTable, MODEL_IDENTIFIER_MACRO_DEFINE)
1285 RecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
1286 for Record in RecordSet:
1287 Name = Record[1].strip().split()[1]
1288 if Name.find('(') != -1:
1289 Name = Name[0:Name.find('(')]
1290 if Name.upper() != Name:
1291 if not EccGlobalData.gException.IsException(ERROR_NAMING_CONVENTION_CHECK_DEFINE_STATEMENT, Name):
1292 EccGlobalData.gDb.TblReport.Insert(ERROR_NAMING_CONVENTION_CHECK_DEFINE_STATEMENT, OtherMsg="The #define name [%s] does not follow the rules" % (Name), BelongsToTable=FileTable, BelongsToItem=Record[0])
1293
1294 # Check whether only capital letters are used for typedef declarations
1295 def NamingConventionCheckTypedefStatement(self, FileTable):
1296 if EccGlobalData.gConfig.NamingConventionCheckTypedefStatement == '1' or EccGlobalData.gConfig.NamingConventionCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
1297 EdkLogger.quiet("Checking naming covention of #typedef statement ...")
1298
1299 SqlCommand = """select ID, Name from %s where Model = %s""" % (FileTable, MODEL_IDENTIFIER_TYPEDEF)
1300 RecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
1301 for Record in RecordSet:
1302 Name = Record[1].strip()
1303 if Name != '' and Name is not None:
1304 if Name[0] == '(':
1305 Name = Name[1:Name.find(')')]
1306 if Name.find('(') > -1:
1307 Name = Name[Name.find('(') + 1 : Name.find(')')]
1308 Name = Name.replace('WINAPI', '')
1309 Name = Name.replace('*', '').strip()
1310 if Name.upper() != Name:
1311 if not EccGlobalData.gException.IsException(ERROR_NAMING_CONVENTION_CHECK_TYPEDEF_STATEMENT, Name):
1312 EccGlobalData.gDb.TblReport.Insert(ERROR_NAMING_CONVENTION_CHECK_TYPEDEF_STATEMENT, OtherMsg="The #typedef name [%s] does not follow the rules" % (Name), BelongsToTable=FileTable, BelongsToItem=Record[0])
1313
1314 # Check whether the #ifndef at the start of an include file uses both prefix and postfix underscore characters, '_'.
1315 def NamingConventionCheckIfndefStatement(self, FileTable):
1316 if EccGlobalData.gConfig.NamingConventionCheckIfndefStatement == '1' or EccGlobalData.gConfig.NamingConventionCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
1317 EdkLogger.quiet("Checking naming covention of #ifndef statement ...")
1318
1319 SqlCommand = """select ID, Value from %s where Model = %s""" % (FileTable, MODEL_IDENTIFIER_MACRO_IFNDEF)
1320 RecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
1321 for Record in RecordSet:
1322 Name = Record[1].replace('#ifndef', '').strip()
1323 if Name[0] != '_' or Name[-1] != '_':
1324 if not EccGlobalData.gException.IsException(ERROR_NAMING_CONVENTION_CHECK_IFNDEF_STATEMENT, Name):
1325 EccGlobalData.gDb.TblReport.Insert(ERROR_NAMING_CONVENTION_CHECK_IFNDEF_STATEMENT, OtherMsg="The #ifndef name [%s] does not follow the rules" % (Name), BelongsToTable=FileTable, BelongsToItem=Record[0])
1326
1327 # Rule for path name, variable name and function name
1328 # 1. First character should be upper case
1329 # 2. Existing lower case in a word
1330 # 3. No space existence
1331 # Check whether the path name followed the rule
1332 def NamingConventionCheckPathName(self):
1333 if EccGlobalData.gConfig.NamingConventionCheckPathName == '1' or EccGlobalData.gConfig.NamingConventionCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
1334 EdkLogger.quiet("Checking naming covention of file path name ...")
1335 Pattern = re.compile(r'^[A-Z]+\S*[a-z]\S*$')
1336 SqlCommand = """select ID, Name from File"""
1337 RecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
1338 for Record in RecordSet:
1339 if not Pattern.match(Record[1]):
1340 if not EccGlobalData.gException.IsException(ERROR_NAMING_CONVENTION_CHECK_PATH_NAME, Record[1]):
1341 EccGlobalData.gDb.TblReport.Insert(ERROR_NAMING_CONVENTION_CHECK_PATH_NAME, OtherMsg="The file path [%s] does not follow the rules" % (Record[1]), BelongsToTable='File', BelongsToItem=Record[0])
1342
1343 # Rule for path name, variable name and function name
1344 # 1. First character should be upper case
1345 # 2. Existing lower case in a word
1346 # 3. No space existence
1347 # 4. Global variable name must start with a 'g'
1348 # Check whether the variable name followed the rule
1349 def NamingConventionCheckVariableName(self, FileTable):
1350 if EccGlobalData.gConfig.NamingConventionCheckVariableName == '1' or EccGlobalData.gConfig.NamingConventionCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
1351 EdkLogger.quiet("Checking naming covention of variable name ...")
1352 Pattern = re.compile(r'^[A-Zgm]+\S*[a-z]\S*$')
1353
1354 SqlCommand = """select ID, Name from %s where Model = %s""" % (FileTable, MODEL_IDENTIFIER_VARIABLE)
1355 RecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
1356 for Record in RecordSet:
1357 Var = Record[1]
1358 if Var.startswith('CONST'):
1359 Var = Var[5:].lstrip()
1360 if not Pattern.match(Var):
1361 if not EccGlobalData.gException.IsException(ERROR_NAMING_CONVENTION_CHECK_VARIABLE_NAME, Record[1]):
1362 EccGlobalData.gDb.TblReport.Insert(ERROR_NAMING_CONVENTION_CHECK_VARIABLE_NAME, OtherMsg="The variable name [%s] does not follow the rules" % (Record[1]), BelongsToTable=FileTable, BelongsToItem=Record[0])
1363
1364 # Rule for path name, variable name and function name
1365 # 1. First character should be upper case
1366 # 2. Existing lower case in a word
1367 # 3. No space existence
1368 # Check whether the function name followed the rule
1369 def NamingConventionCheckFunctionName(self):
1370 if EccGlobalData.gConfig.NamingConventionCheckFunctionName == '1' or EccGlobalData.gConfig.NamingConventionCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
1371 EdkLogger.quiet("Checking naming covention of function name ...")
1372 Pattern = re.compile(r'^[A-Z]+\S*[a-z]\S*$')
1373 SqlCommand = """select ID, Name from Function"""
1374 RecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
1375 for Record in RecordSet:
1376 if not Pattern.match(Record[1]):
1377 if not EccGlobalData.gException.IsException(ERROR_NAMING_CONVENTION_CHECK_FUNCTION_NAME, Record[1]):
1378 EccGlobalData.gDb.TblReport.Insert(ERROR_NAMING_CONVENTION_CHECK_FUNCTION_NAME, OtherMsg="The function name [%s] does not follow the rules" % (Record[1]), BelongsToTable='Function', BelongsToItem=Record[0])
1379
1380 # Check whether NO use short variable name with single character
1381 def NamingConventionCheckSingleCharacterVariable(self, FileTable):
1382 if EccGlobalData.gConfig.NamingConventionCheckSingleCharacterVariable == '1' or EccGlobalData.gConfig.NamingConventionCheckAll == '1' or EccGlobalData.gConfig.CheckAll == '1':
1383 EdkLogger.quiet("Checking naming covention of single character variable name ...")
1384
1385 SqlCommand = """select ID, Name from %s where Model = %s""" % (FileTable, MODEL_IDENTIFIER_VARIABLE)
1386 RecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand)
1387 for Record in RecordSet:
1388 Variable = Record[1].replace('*', '')
1389 if len(Variable) == 1:
1390 if not EccGlobalData.gException.IsException(ERROR_NAMING_CONVENTION_CHECK_SINGLE_CHARACTER_VARIABLE, Record[1]):
1391 EccGlobalData.gDb.TblReport.Insert(ERROR_NAMING_CONVENTION_CHECK_SINGLE_CHARACTER_VARIABLE, OtherMsg="The variable name [%s] does not follow the rules" % (Record[1]), BelongsToTable=FileTable, BelongsToItem=Record[0])
1392
1393 def FindPara(FilePath, Para, CallingLine):
1394 Lines = open(FilePath).readlines()
1395 Line = ''
1396 for Index in range(CallingLine - 1, 0, -1):
1397 # Find the nearest statement for Para
1398 Line = Lines[Index].strip()
1399 if Line.startswith('%s = ' % Para):
1400 Line = Line.strip()
1401 return Line
1402 break
1403
1404 return ''
1405
1406 ##
1407 #
1408 # This acts like the main() function for the script, unless it is 'import'ed into another
1409 # script.
1410 #
1411 if __name__ == '__main__':
1412 Check = Check()
1413 Check.Check()