summaryrefslogtreecommitdiff
path: root/BaseTools/Source/Python/Eot/Parser.py
blob: b0b3d0b6e1b3eacbcb059a8da138540362a16718 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
## @file
# This file is used to define common parsing related functions used in parsing
# Inf/Dsc/Makefile process
#
# Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#

##
# Import Modules
#
from __future__ import absolute_import
import Common.LongFilePathOs as os, re
import Common.EdkLogger as EdkLogger
from Common.DataType import *
from CommonDataClass.DataClass import *
from Common.StringUtils import CleanString, GetSplitValueList, ReplaceMacro
from . import EotGlobalData
from Common.StringUtils import GetSplitList
from Common.LongFilePathSupport import OpenLongFilePath as open

import subprocess

## DeCompress
#
# Call external decompress tool to decompress the fv section
#
def DeCompress(Method, Input):
    # Write the input to a temp file
    open('_Temp.bin', 'wb').write(Input)
    cmd = ''
    if Method == 'Lzma':
        cmd = r'LzmaCompress -o _New.bin -d _Temp.bin'
    if Method == 'Efi':
        cmd = r'TianoCompress -d --uefi -o _New.bin _Temp.bin'
    if Method == 'Framework':
        cmd = r'TianoCompress -d -o _New.bin _Temp.bin'

    # Call tool to create the decompressed output file
    Process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    Process.communicate()[0]

    # Return the beffer of New.bin
    if os.path.exists('_New.bin'):
        return open('_New.bin', 'rb').read()


## PreProcess() method
#
#  Pre process a file
#
#  1. Remove all comments
#  2. Merge multiple lines code to one line
#
#  @param  Filename: Name of the file to be parsed
#  @param  MergeMultipleLines: Switch for if merge multiple lines
#  @param  LineNo: Default line no
#
#  @return Lines: The file contents after removing comments
#
def PreProcess(Filename, MergeMultipleLines = True, LineNo = -1):
    Lines = []
    Filename = os.path.normpath(Filename)
    if not os.path.isfile(Filename):
        EdkLogger.error("Eot", EdkLogger.FILE_NOT_FOUND, ExtraData=Filename)

    IsFindBlockComment = False
    IsFindBlockCode = False
    ReservedLine = ''
    ReservedLineLength = 0
    for Line in open(Filename, 'r'):
        Line = Line.strip()
        # Remove comment block
        if Line.find(TAB_COMMENT_EDK_START) > -1:
            ReservedLine = GetSplitList(Line, TAB_COMMENT_EDK_START, 1)[0]
            IsFindBlockComment = True
        if Line.find(TAB_COMMENT_EDK_END) > -1:
            Line = ReservedLine + GetSplitList(Line, TAB_COMMENT_EDK_END, 1)[1]
            ReservedLine = ''
            IsFindBlockComment = False
        if IsFindBlockComment:
            Lines.append('')
            continue

        # Remove comments at tail and remove spaces again
        Line = CleanString(Line)
        if Line == '':
            Lines.append('')
            continue

        if MergeMultipleLines:
            # Add multiple lines to one line
            if IsFindBlockCode and Line[-1] != TAB_SLASH:
                ReservedLine = (ReservedLine + TAB_SPACE_SPLIT + Line).strip()
                Lines.append(ReservedLine)
                for Index in (0, ReservedLineLength):
                    Lines.append('')
                ReservedLine = ''
                ReservedLineLength = 0
                IsFindBlockCode = False
                continue
            if Line[-1] == TAB_SLASH:
                ReservedLine = ReservedLine +  TAB_SPACE_SPLIT + Line[0:-1].strip()
                ReservedLineLength = ReservedLineLength + 1
                IsFindBlockCode = True
                continue

        Lines.append(Line)

    return Lines

## AddToSelfMacro() method
#
#  Parse a line of macro definition and add it to a macro set
#
#  @param  SelfMacro: The self macro set
#  @param  Line: The line of a macro definition
#
#  @return Name: Name of macro
#  @return Value: Value of macro
#
def AddToSelfMacro(SelfMacro, Line):
    Name, Value = '', ''
    List = GetSplitValueList(Line, TAB_EQUAL_SPLIT, 1)
    if len(List) == 2:
        Name = List[0]
        Value = List[1]
        Value = ReplaceMacro(Value, EotGlobalData.gMACRO, True)
        Value = ReplaceMacro(Value, SelfMacro, True)
        SelfMacro[Name] = Value

    return (Name, Value)

## GetIncludeListOfFile() method
#
#  Get the include path list for a source file
#
#  1. Find the source file belongs to which INF file
#  2. Find the inf's package
#  3. Return the include path list of the package
#
#  @param  WorkSpace: WORKSPACE path
#  @param  Filepath: File path
#  @param  Db: Eot database
#
#  @return IncludeList: A list of include directories
#
def GetIncludeListOfFile(WorkSpace, Filepath, Db):
    IncludeList = []
    Filepath = os.path.normpath(Filepath)
    SqlCommand = """
                select Value1 from Inf where Model = %s and BelongsToFile in(
                    select distinct B.BelongsToFile from File as A left join Inf as B
                        where A.ID = B.BelongsToFile and B.Model = %s and (A.Path || '%s' || B.Value1) = '%s')""" \
                % (MODEL_META_DATA_PACKAGE, MODEL_EFI_SOURCE_FILE, '\\', Filepath)
    RecordSet = Db.TblFile.Exec(SqlCommand)
    for Record in RecordSet:
        DecFullPath = os.path.normpath(os.path.join(WorkSpace, Record[0]))
        (DecPath, DecName) = os.path.split(DecFullPath)
        SqlCommand = """select Value1 from Dec where BelongsToFile =
                           (select ID from File where FullPath = '%s') and Model = %s""" \
                    % (DecFullPath, MODEL_EFI_INCLUDE)
        NewRecordSet = Db.TblDec.Exec(SqlCommand)
        for NewRecord in NewRecordSet:
            IncludePath = os.path.normpath(os.path.join(DecPath, NewRecord[0]))
            if IncludePath not in IncludeList:
                IncludeList.append(IncludePath)

    return IncludeList

## GetTableList() method
#
#  Search table file and find all small tables
#
#  @param  FileModelList: Model code for the file list
#  @param  Table: Table to insert records
#  @param  Db: Eot database
#
#  @return TableList: A list of tables
#
def GetTableList(FileModelList, Table, Db):
    TableList = []
    SqlCommand = """select ID, FullPath from File where Model in %s""" % str(FileModelList)
    RecordSet = Db.TblFile.Exec(SqlCommand)
    for Record in RecordSet:
        TableName = Table + str(Record[0])
        TableList.append([TableName, Record[1]])

    return TableList

## GetAllIncludeDir() method
#
#  Find all Include directories
#
#  @param  Db: Eot database
#
#  @return IncludeList: A list of include directories
#
def GetAllIncludeDirs(Db):
    IncludeList = []
    SqlCommand = """select distinct Value1 from Inf where Model = %s order by Value1""" % MODEL_EFI_INCLUDE
    RecordSet = Db.TblInf.Exec(SqlCommand)

    for Record in RecordSet:
        IncludeList.append(Record[0])

    return IncludeList

## GetAllIncludeFiles() method
#
#  Find all Include files
#
#  @param  Db: Eot database
#
#  @return IncludeFileList: A list of include files
#
def GetAllIncludeFiles(Db):
    IncludeList = GetAllIncludeDirs(Db)
    IncludeFileList = []

    for Dir in IncludeList:
        if os.path.isdir(Dir):
            SubDir = os.listdir(Dir)
            for Item in SubDir:
                if os.path.isfile(Item):
                    IncludeFileList.append(Item)

    return IncludeFileList

## SearchBelongsToFunction() method
#
#  Search all functions belong to the file
#
#  @param BelongsToFile: File id
#  @param StartLine: Start line of search scope
#  @param EndLine: End line of search scope
#
#  @return: The found function
#
def SearchBelongsToFunction(BelongsToFile, StartLine, EndLine):
    SqlCommand = """select ID, Name from Function where BelongsToFile = %s and StartLine <= %s and EndLine >= %s""" %(BelongsToFile, StartLine, EndLine)
    RecordSet = EotGlobalData.gDb.TblFunction.Exec(SqlCommand)
    if RecordSet != []:
        return RecordSet[0][0], RecordSet[0][1]
    else:
        return -1, ''

## SearchPpiCallFunction() method
#
#  Search all used PPI calling function 'PeiServicesReInstallPpi' and 'PeiServicesInstallPpi'
#  Store the result to database
#
#  @param Identifier: Table id
#  @param SourceFileID: Source file id
#  @param SourceFileFullPath: Source file full path
#  @param ItemMode: Mode of the item
#
def SearchPpiCallFunction(Identifier, SourceFileID, SourceFileFullPath, ItemMode):
    ItemName, ItemType, GuidName, GuidMacro, GuidValue = '', 'Ppi', '', '', ''
    SqlCommand = """select Value, Name, BelongsToFile, StartLine, EndLine from %s
                    where (Name like '%%%s%%' and Model = %s)""" \
                    % (Identifier, 'PeiServicesReInstallPpi', MODEL_IDENTIFIER_FUNCTION_CALLING)
    BelongsToFunctionID, BelongsToFunction = -1, ''
    Db = EotGlobalData.gDb.TblReport
    RecordSet = Db.Exec(SqlCommand)
    for Record in RecordSet:
        Index = 0
        BelongsToFile, StartLine, EndLine = Record[2], Record[3], Record[4]
        BelongsToFunctionID, BelongsToFunction = SearchBelongsToFunction(BelongsToFile, StartLine, EndLine)
        VariableList = Record[0].split(',')
        for Variable in VariableList:
            Variable = Variable.strip()
            # Get index of the variable
            if Variable.find('[') > -1:
                Index = int(Variable[Variable.find('[') + 1 : Variable.find(']')])
                Variable = Variable[:Variable.find('[')]
            # Get variable name
            if Variable.startswith('&'):
                Variable = Variable[1:]
            # Get variable value
            SqlCommand = """select Value from %s where (Name like '%%%s%%') and Model = %s""" \
                         % (Identifier, Variable, MODEL_IDENTIFIER_VARIABLE)
            NewRecordSet = Db.Exec(SqlCommand)
            if NewRecordSet:
                NewRecord = NewRecordSet[0][0]
                VariableValueList = NewRecord.split('},')
                if len(VariableValueList) > Index:
                    VariableValue = VariableValueList[Index]
                    NewVariableValueList = VariableValue.split(',')
                    if len(NewVariableValueList) > 1:
                        NewVariableValue = NewVariableValueList[1].strip()
                        if NewVariableValue.startswith('&'):
                            Db.Insert(-1, '', '', SourceFileID, SourceFileFullPath, ItemName, ItemType, ItemMode, NewVariableValue[1:], GuidMacro, GuidValue, BelongsToFunction, 0)
                            continue
                        else:
                            EotGlobalData.gOP_UN_MATCHED.write('%s, %s, %s, %s, %s, %s\n' % (ItemType, ItemMode, SourceFileID, SourceFileFullPath, StartLine, NewParameter))

    ItemName, ItemType, GuidName, GuidMacro, GuidValue = '', 'Ppi', '', '', ''
    SqlCommand = """select Value, Name, BelongsToFile, StartLine, EndLine from %s
                    where (Value like '%%%s%%' and Model = %s)""" \
                    % (Identifier, 'PeiServicesInstallPpi', MODEL_IDENTIFIER_ASSIGNMENT_EXPRESSION)
    BelongsToFunctionID, BelongsToFunction = -1, ''
    Db = EotGlobalData.gDb.TblReport
    RecordSet = Db.Exec(SqlCommand)

    SqlCommand = """select Value, Name, BelongsToFile, StartLine, EndLine from %s
                    where (Name like '%%%s%%' and Model = %s)""" \
                    % (Identifier, 'PeiServicesInstallPpi', MODEL_IDENTIFIER_FUNCTION_CALLING)
    Db = EotGlobalData.gDb.TblReport
    RecordSet2 = Db.Exec(SqlCommand)

    for Record in RecordSet + RecordSet2:
        if Record == []:
            continue
        Index = 0
        BelongsToFile, StartLine, EndLine = Record[2], Record[3], Record[4]
        BelongsToFunctionID, BelongsToFunction = SearchBelongsToFunction(BelongsToFile, StartLine, EndLine)
        Variable = Record[0].replace('PeiServicesInstallPpi', '').replace('(', '').replace(')', '').replace('&', '').strip()
        Variable = Variable[Variable.find(',') + 1:].strip()
        # Get index of the variable
        if Variable.find('[') > -1:
            Index = int(Variable[Variable.find('[') + 1 : Variable.find(']')])
            Variable = Variable[:Variable.find('[')]
        # Get variable name
        if Variable.startswith('&'):
            Variable = Variable[1:]
        # Get variable value
        SqlCommand = """select Value from %s where (Name like '%%%s%%') and Model = %s""" \
                     % (Identifier, Variable, MODEL_IDENTIFIER_VARIABLE)
        NewRecordSet = Db.Exec(SqlCommand)
        if NewRecordSet:
            NewRecord = NewRecordSet[0][0]
            VariableValueList = NewRecord.split('},')
            for VariableValue in VariableValueList[Index:]:
                NewVariableValueList = VariableValue.split(',')
                if len(NewVariableValueList) > 1:
                    NewVariableValue = NewVariableValueList[1].strip()
                    if NewVariableValue.startswith('&'):
                        Db.Insert(-1, '', '', SourceFileID, SourceFileFullPath, ItemName, ItemType, ItemMode, NewVariableValue[1:], GuidMacro, GuidValue, BelongsToFunction, 0)
                        continue
                    else:
                        EotGlobalData.gOP_UN_MATCHED.write('%s, %s, %s, %s, %s, %s\n' % (ItemType, ItemMode, SourceFileID, SourceFileFullPath, StartLine, NewParameter))

## SearchPpis() method
#
#  Search all used PPI calling function
#  Store the result to database
#
#  @param SqlCommand: SQL command statement
#  @param Table: Table id
#  @param SourceFileID: Source file id
#  @param SourceFileFullPath: Source file full path
#  @param ItemMode: Mode of the item
#  @param PpiMode: Mode of PPI
#
def SearchPpi(SqlCommand, Table, SourceFileID, SourceFileFullPath, ItemMode, PpiMode = 1):
    ItemName, ItemType, GuidName, GuidMacro, GuidValue = '', 'Ppi', '', '', ''
    BelongsToFunctionID, BelongsToFunction = -1, ''
    Db = EotGlobalData.gDb.TblReport
    RecordSet = Db.Exec(SqlCommand)
    for Record in RecordSet:
        Parameter = GetPpiParameter(Record[0], PpiMode)
        BelongsToFile, StartLine, EndLine = Record[2], Record[3], Record[4]
        # Get BelongsToFunction
        BelongsToFunctionID, BelongsToFunction = SearchBelongsToFunction(BelongsToFile, StartLine, EndLine)

        # Default is Not Found
        IsFound = False

        # For Consumed Ppi
        if ItemMode == 'Consumed':
            if Parameter.startswith('g'):
                Db.Insert(-1, '', '', SourceFileID, SourceFileFullPath, ItemName, ItemType, ItemMode, Parameter, GuidMacro, GuidValue, BelongsToFunction, 0)
            else:
                EotGlobalData.gOP_UN_MATCHED.write('%s, %s, %s, %s, %s, %s\n' % (ItemType, ItemMode, SourceFileID, SourceFileFullPath, StartLine, Parameter))
            continue

        # Direct Parameter.Guid
        SqlCommand = """select Value from %s where (Name like '%%%s.Guid%%' or Name like '%%%s->Guid%%') and Model = %s""" % (Table, Parameter, Parameter, MODEL_IDENTIFIER_ASSIGNMENT_EXPRESSION)
        NewRecordSet = Db.Exec(SqlCommand)
        for NewRecord in NewRecordSet:
            GuidName = GetParameterName(NewRecord[0])
            Db.Insert(-1, '', '', SourceFileID, SourceFileFullPath, ItemName, ItemType, ItemMode, GuidName, GuidMacro, GuidValue, BelongsToFunction, 0)
            IsFound = True

        # Defined Parameter
        if not IsFound:
            Key = Parameter
            if Key.rfind(' ') > -1:
                Key = Key[Key.rfind(' ') : ].strip().replace('&', '')
            Value = FindKeyValue(EotGlobalData.gDb.TblFile, Table, Key)
            List = GetSplitValueList(Value.replace('\n', ''), TAB_COMMA_SPLIT)
            if len(List) > 1:
                GuidName = GetParameterName(List[1])
                Db.Insert(-1, '', '', SourceFileID, SourceFileFullPath, ItemName, ItemType, ItemMode, GuidName, GuidMacro, GuidValue, BelongsToFunction, 0)
                IsFound = True

        # A list Parameter
        if not IsFound:
            Start = Parameter.find('[')
            End = Parameter.find(']')
            if Start > -1 and End > -1 and Start < End:
                try:
                    Index = int(Parameter[Start + 1 : End])
                    Parameter = Parameter[0 : Start]
                    SqlCommand = """select Value from %s where Name = '%s' and Model = %s""" % (Table, Parameter, MODEL_IDENTIFIER_VARIABLE)
                    NewRecordSet = Db.Exec(SqlCommand)
                    for NewRecord in NewRecordSet:
                        NewParameter = GetSplitValueList(NewRecord[0], '}')[Index]
                        GuidName = GetPpiParameter(NewParameter[NewParameter.find('{') : ])
                        Db.Insert(-1, '', '', SourceFileID, SourceFileFullPath, ItemName, ItemType, ItemMode, GuidName, GuidMacro, GuidValue, BelongsToFunction, 0)
                        IsFound = True
                except Exception:
                    pass

        # A External Parameter
        if not IsFound:
            SqlCommand = """select File.ID from Inf, File
                            where BelongsToFile = (select BelongsToFile from Inf where Value1 = '%s')
                            and Inf.Model = %s and Inf.Value1 = File.FullPath and File.Model = %s""" % (SourceFileFullPath, MODEL_EFI_SOURCE_FILE, MODEL_FILE_C)
            NewRecordSet = Db.Exec(SqlCommand)
            for NewRecord in NewRecordSet:
                Table = 'Identifier' + str(NewRecord[0])
                SqlCommand = """select Value from %s where Name = '%s' and Modifier = 'EFI_PEI_PPI_DESCRIPTOR' and Model = %s""" % (Table, Parameter, MODEL_IDENTIFIER_VARIABLE)
                PpiSet = Db.Exec(SqlCommand)
                if PpiSet != []:
                    GuidName = GetPpiParameter(PpiSet[0][0])
                    if GuidName != '':
                        Db.Insert(-1, '', '', SourceFileID, SourceFileFullPath, ItemName, ItemType, ItemMode, GuidName, GuidMacro, GuidValue, BelongsToFunction, 0)
                        IsFound = True
                        break

        if not IsFound:
            EotGlobalData.gOP_UN_MATCHED.write('%s, %s, %s, %s, %s, %s\n' % (ItemType, ItemMode, SourceFileID, SourceFileFullPath, StartLine, Parameter))

## SearchProtocols() method
#
#  Search all used PROTOCOL calling function
#  Store the result to database
#
#  @param SqlCommand: SQL command statement
#  @param Table: Table id
#  @param SourceFileID: Source file id
#  @param SourceFileFullPath: Source file full path
#  @param ItemMode: Mode of the item
#  @param ProtocolMode: Mode of PROTOCOL
#
def SearchProtocols(SqlCommand, Table, SourceFileID, SourceFileFullPath, ItemMode, ProtocolMode):
    ItemName, ItemType, GuidName, GuidMacro, GuidValue = '', 'Protocol', '', '', ''
    BelongsToFunctionID, BelongsToFunction = -1, ''
    Db = EotGlobalData.gDb.TblReport
    RecordSet = Db.Exec(SqlCommand)
    for Record in RecordSet:
        Parameter = ''
        BelongsToFile, StartLine, EndLine = Record[2], Record[3], Record[4]
        # Get BelongsToFunction
        BelongsToFunctionID, BelongsToFunction = SearchBelongsToFunction(BelongsToFile, StartLine, EndLine)

        # Default is Not Found
        IsFound = False

        if ProtocolMode == 0 or ProtocolMode == 1:
            Parameter = GetProtocolParameter(Record[0], ProtocolMode)
            if Parameter.startswith('g') or Parameter.endswith('Guid') or Parameter == 'ShellEnvProtocol' or Parameter == 'ShellInterfaceProtocol':
                GuidName = GetParameterName(Parameter)
                Db.Insert(-1, '', '', SourceFileID, SourceFileFullPath, ItemName, ItemType, ItemMode, GuidName, GuidMacro, GuidValue, BelongsToFunction, 0)
                IsFound = True

        if ProtocolMode == 2:
            Protocols = GetSplitValueList(Record[0], TAB_COMMA_SPLIT)
            for Protocol in Protocols:
                if Protocol.startswith('&') and Protocol.endswith('Guid'):
                    GuidName = GetParameterName(Protocol)
                    Db.Insert(-1, '', '', SourceFileID, SourceFileFullPath, ItemName, ItemType, ItemMode, GuidName, GuidMacro, GuidValue, BelongsToFunction, 0)
                    IsFound = True
                else:
                    NewValue = FindKeyValue(EotGlobalData.gDb.TblFile, Table, Protocol)
                    if Protocol != NewValue and NewValue.endswith('Guid'):
                        GuidName = GetParameterName(NewValue)
                        Db.Insert(-1, '', '', SourceFileID, SourceFileFullPath, ItemName, ItemType, ItemMode, GuidName, GuidMacro, GuidValue, BelongsToFunction, 0)
                        IsFound = True

        if not IsFound:
            if BelongsToFunction in EotGlobalData.gProducedProtocolLibrary or BelongsToFunction in EotGlobalData.gConsumedProtocolLibrary:
                EotGlobalData.gOP_UN_MATCHED_IN_LIBRARY_CALLING.write('%s, %s, %s, %s, %s, %s, %s\n' % (ItemType, ItemMode, SourceFileID, SourceFileFullPath, StartLine, Parameter, BelongsToFunction))
            else:
                EotGlobalData.gOP_UN_MATCHED.write('%s, %s, %s, %s, %s, %s\n' % (ItemType, ItemMode, SourceFileID, SourceFileFullPath, StartLine, Parameter))

## SearchFunctionCalling() method
#
#  Search all used PPI/PROTOCOL calling function by library
#  Store the result to database
#
#  @param SqlCommand: SQL command statement
#  @param Table: Table id
#  @param SourceFileID: Source file id
#  @param SourceFileFullPath: Source file full path
#  @param ItemType: Type of the item, PPI or PROTOCOL
#  @param ItemMode: Mode of item
#
def SearchFunctionCalling(Table, SourceFileID, SourceFileFullPath, ItemType, ItemMode):
    LibraryList = {}
    Db = EotGlobalData.gDb.TblReport
    Parameters, ItemName, GuidName, GuidMacro, GuidValue, BelongsToFunction = [], '', '', '', '', ''
    if ItemType == 'Protocol' and ItemMode == 'Produced':
        LibraryList = EotGlobalData.gProducedProtocolLibrary
    elif ItemType == 'Protocol' and ItemMode == 'Consumed':
        LibraryList = EotGlobalData.gConsumedProtocolLibrary
    elif ItemType == 'Protocol' and ItemMode == 'Callback':
        LibraryList = EotGlobalData.gCallbackProtocolLibrary
    elif ItemType == 'Ppi' and ItemMode == 'Produced':
        LibraryList = EotGlobalData.gProducedPpiLibrary
    elif ItemType == 'Ppi' and ItemMode == 'Consumed':
        LibraryList = EotGlobalData.gConsumedPpiLibrary

    for Library in LibraryList:
        Index = LibraryList[Library]
        SqlCommand = """select Value, StartLine from %s
                        where Name like '%%%s%%' and Model = %s""" \
                        % (Table, Library, MODEL_IDENTIFIER_FUNCTION_CALLING)
        RecordSet = Db.Exec(SqlCommand)
        for Record in RecordSet:
            IsFound = False
            if Index == -1:
                ParameterList = GetSplitValueList(Record[0], TAB_COMMA_SPLIT)
                for Parameter in ParameterList:
                    Parameters.append(GetParameterName(Parameter))
            else:
                Parameters = [GetProtocolParameter(Record[0], Index)]
            StartLine = Record[1]
            for Parameter in Parameters:
                if Parameter.startswith('g') or Parameter.endswith('Guid') or Parameter == 'ShellEnvProtocol' or Parameter == 'ShellInterfaceProtocol':
                    GuidName = GetParameterName(Parameter)
                    Db.Insert(-1, '', '', SourceFileID, SourceFileFullPath, ItemName, ItemType, ItemMode, GuidName, GuidMacro, GuidValue, BelongsToFunction, 0)
                    IsFound = True

            if not IsFound:
                EotGlobalData.gOP_UN_MATCHED.write('%s, %s, %s, %s, %s, %s\n' % (ItemType, ItemMode, SourceFileID, SourceFileFullPath, StartLine, Parameter))

## FindProtocols() method
#
#  Find defined protocols
#
#  @param SqlCommand: SQL command statement
#  @param Table: Table id
#  @param SourceFileID: Source file id
#  @param SourceFileFullPath: Source file full path
#  @param ItemName: String of protocol definition
#  @param ItemType: Type of the item, PPI or PROTOCOL
#  @param ItemMode: Mode of item
#
#def FindProtocols(Db, SqlCommand, Table, SourceFileID, SourceFileFullPath, ItemName, ItemType, ItemMode, GuidName, GuidMacro, GuidValue):
#    BelongsToFunction = ''
#    RecordSet = Db.Exec(SqlCommand)
#    for Record in RecordSet:
#        IsFound = True
#        Parameter = GetProtocolParameter(Record[0])

## GetProtocolParameter() method
#
# Parse string of protocol and find parameters
#
#  @param Parameter: Parameter to be parsed
#  @param Index: The index of the parameter
#
#  @return: call common GetParameter
#
def GetProtocolParameter(Parameter, Index = 1):
    return GetParameter(Parameter, Index)

## GetPpiParameter() method
#
# Parse string of ppi and find parameters
#
#  @param Parameter: Parameter to be parsed
#  @param Index: The index of the parameter
#
#  @return: call common GetParameter
#
def GetPpiParameter(Parameter, Index = 1):
    return GetParameter(Parameter, Index)

## GetParameter() method
#
# Get a parameter by index
#
#  @param Parameter: Parameter to be parsed
#  @param Index: The index of the parameter
#
#  @return Parameter: The found parameter
#
def GetParameter(Parameter, Index = 1):
    ParameterList = GetSplitValueList(Parameter, TAB_COMMA_SPLIT)
    if len(ParameterList) > Index:
        Parameter = GetParameterName(ParameterList[Index])

        return Parameter

    return ''

## GetParameterName() method
#
# Get a parameter name
#
#  @param Parameter: Parameter to be parsed
#
#  @return: The name of parameter
#
def GetParameterName(Parameter):
    if isinstance(Parameter, type('')) and Parameter.startswith('&'):
        return Parameter[1:].replace('{', '').replace('}', '').replace('\r', '').replace('\n', '').strip()
    else:
        return Parameter.strip()

## FindKeyValue() method
#
# Find key value of a variable
#
#  @param Db: Database to be searched
#  @param Table: Table to be searched
#  @param Key: The keyword
#
#  @return Value: The value of the keyword
#
def FindKeyValue(Db, Table, Key):
    SqlCommand = """select Value from %s where Name = '%s' and (Model = %s or Model = %s)""" % (Table, Key, MODEL_IDENTIFIER_VARIABLE, MODEL_IDENTIFIER_ASSIGNMENT_EXPRESSION)
    RecordSet = Db.Exec(SqlCommand)
    Value = ''
    for Record in RecordSet:
        if Record[0] != 'NULL':
            Value = FindKeyValue(Db, Table, GetParameterName(Record[0]))

    if Value != '':
        return Value
    else:
        return Key

## ParseMapFile() method
#
#  Parse map files to get a dict of 'ModuleName' : {FunName : FunAddress}
#
#  @param Files: A list of map files
#
#  @return AllMaps: An object of all map files
#
def ParseMapFile(Files):
    AllMaps = {}
    CurrentModule = ''
    CurrentMaps = {}
    for File in Files:
        Content = open(File, 'r').readlines()
        for Line in Content:
            Line = CleanString(Line)
            # skip empty line
            if Line == '':
                continue

            if Line.find('(') > -1 and Line.find(')') > -1:
                if CurrentModule != '' and CurrentMaps != {}:
                    AllMaps[CurrentModule] = CurrentMaps
                CurrentModule = Line[:Line.find('(')]
                CurrentMaps = {}
                continue
            else:
                Name = ''
                Address = ''
                List = Line.split()
                Address = List[0]
                if List[1] == 'F' or List[1] == 'FS':
                    Name = List[2]
                else:
                    Name = List[1]
                CurrentMaps[Name] = Address
                continue

    return AllMaps

##
#
# This acts like the main() function for the script, unless it is 'import'ed into another
# script.
#
if __name__ == '__main__':
    pass