1## @file
2#
3# This package manage the VPD PCD information file which will be generated
4# by build tool's autogen.
5# The VPD PCD information file will be input for third-party BPDG tool which
6# is pointed by *_*_*_VPD_TOOL_GUID in conf/tools_def.txt
7#
8#
9# Copyright (c) 2010 - 2014, Intel Corporation. All rights reserved.<BR>
10# This program and the accompanying materials
11# are licensed and made available under the terms and conditions of the BSD License
12# which accompanies this distribution.  The full text of the license may be found at
13# http://opensource.org/licenses/bsd-license.php
14#
15# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
16# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
17#
18import Common.LongFilePathOs as os
19import re
20import Common.EdkLogger as EdkLogger
21import Common.BuildToolError as BuildToolError
22import subprocess
23from Common.LongFilePathSupport import OpenLongFilePath as open
24
25FILE_COMMENT_TEMPLATE = \
26"""
27## @file
28#
29#  THIS IS AUTO-GENERATED FILE BY BUILD TOOLS AND PLEASE DO NOT MAKE MODIFICATION.
30#
31#  This file lists all VPD informations for a platform collected by build.exe.
32#
33# Copyright (c) 2010, Intel Corporation. All rights reserved.<BR>
34# This program and the accompanying materials
35# are licensed and made available under the terms and conditions of the BSD License
36# which accompanies this distribution.  The full text of the license may be found at
37# http://opensource.org/licenses/bsd-license.php
38#
39# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
40# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
41#
42
43"""
44
45## The class manage VpdInfoFile.
46#
47#  This file contains an ordered (based on position in the DSC file) list of the PCDs specified in the platform description file (DSC). The Value field that will be assigned to the PCD comes from the DSC file, INF file (if not defined in the DSC file) or the DEC file (if not defined in the INF file). This file is used as an input to the BPDG tool.
48#  Format for this file (using EBNF notation) is:
49#  <File>            :: = [<CommentBlock>]
50#                         [<PcdEntry>]*
51#  <CommentBlock>    ::=  ["#" <String> <EOL>]*
52#  <PcdEntry>        ::=  <PcdName> "|" <Offset> "|" <Size> "|" <Value> <EOL>
53#  <PcdName>         ::=  <TokenSpaceCName> "." <PcdCName>
54#  <TokenSpaceCName> ::=  C Variable Name of the Token Space GUID
55#  <PcdCName>        ::=  C Variable Name of the PCD
56#  <Offset>          ::=  {"*"} {<HexNumber>}
57#  <HexNumber>       ::=  "0x" (a-fA-F0-9){1,8}
58#  <Size>            ::=  <HexNumber>
59#  <Value>           ::=  {<HexNumber>} {<NonNegativeInt>} {<QString>} {<Array>}
60#  <NonNegativeInt>  ::=  (0-9)+
61#  <QString>         ::=  ["L"] <DblQuote> <String> <DblQuote>
62#  <DblQuote>        ::=  0x22
63#  <Array>           ::=  {<CArray>} {<NList>}
64#  <CArray>          ::=  "{" <HexNumber> ["," <HexNumber>]* "}"
65#  <NList>           ::=  <HexNumber> ["," <HexNumber>]*
66#
67class VpdInfoFile:
68
69    ## The mapping dictionary from datum type to size string.
70    _MAX_SIZE_TYPE = {"BOOLEAN":"1", "UINT8":"1", "UINT16":"2", "UINT32":"4", "UINT64":"8"}
71    _rVpdPcdLine = None
72    ## Constructor
73    def __init__(self):
74        ## Dictionary for VPD in following format
75        #
76        #  Key    : PcdClassObject instance.
77        #           @see BuildClassObject.PcdClassObject
78        #  Value  : offset in different SKU such as [sku1_offset, sku2_offset]
79        self._VpdArray = {}
80
81    ## Add a VPD PCD collected from platform's autogen when building.
82    #
83    #  @param vpds  The list of VPD PCD collected for a platform.
84    #               @see BuildClassObject.PcdClassObject
85    #
86    #  @param offset integer value for VPD's offset in specific SKU.
87    #
88    def Add(self, Vpd, Offset):
89        if (Vpd == None):
90            EdkLogger.error("VpdInfoFile", BuildToolError.ATTRIBUTE_UNKNOWN_ERROR, "Invalid VPD PCD entry.")
91
92        if not (Offset >= 0 or Offset == "*"):
93            EdkLogger.error("VpdInfoFile", BuildToolError.PARAMETER_INVALID, "Invalid offset parameter: %s." % Offset)
94
95        if Vpd.DatumType == "VOID*":
96            if Vpd.MaxDatumSize <= 0:
97                EdkLogger.error("VpdInfoFile", BuildToolError.PARAMETER_INVALID,
98                                "Invalid max datum size for VPD PCD %s.%s" % (Vpd.TokenSpaceGuidCName, Vpd.TokenCName))
99        elif Vpd.DatumType in ["BOOLEAN", "UINT8", "UINT16", "UINT32", "UINT64"]:
100            if Vpd.MaxDatumSize == None or Vpd.MaxDatumSize == "":
101                Vpd.MaxDatumSize = VpdInfoFile._MAX_SIZE_TYPE[Vpd.DatumType]
102        else:
103            EdkLogger.error("VpdInfoFile", BuildToolError.PARAMETER_INVALID,
104                            "Invalid DatumType %s for VPD PCD %s.%s" % (Vpd.DatumType, Vpd.TokenSpaceGuidCName, Vpd.TokenCName))
105
106        if Vpd not in self._VpdArray.keys():
107            #
108            # If there is no Vpd instance in dict, that imply this offset for a given SKU is a new one
109            #
110            self._VpdArray[Vpd] = [Offset]
111        else:
112            #
113            # If there is an offset for a specific SKU in dict, then append this offset for other sku to array.
114            #
115            self._VpdArray[Vpd].append(Offset)
116
117
118    ## Generate VPD PCD information into a text file
119    #
120    #  If parameter FilePath is invalid, then assert.
121    #  If
122    #  @param FilePath        The given file path which would hold VPD information
123    def Write(self, FilePath):
124        if not (FilePath != None or len(FilePath) != 0):
125            EdkLogger.error("VpdInfoFile", BuildToolError.PARAMETER_INVALID,
126                            "Invalid parameter FilePath: %s." % FilePath)
127        try:
128            fd = open(FilePath, "w")
129        except:
130            EdkLogger.error("VpdInfoFile",
131                            BuildToolError.FILE_OPEN_FAILURE,
132                            "Fail to open file %s for written." % FilePath)
133
134        try:
135            # write file header
136            fd.write(FILE_COMMENT_TEMPLATE)
137
138            # write each of PCD in VPD type
139            Pcds = self._VpdArray.keys()
140            Pcds.sort()
141            for Pcd in Pcds:
142                i = 0
143                for Offset in self._VpdArray[Pcd]:
144                    PcdValue = str(Pcd.SkuInfoList[Pcd.SkuInfoList.keys()[i]].DefaultValue).strip()
145                    if PcdValue == "" :
146                        PcdValue  = Pcd.DefaultValue
147
148                    fd.write("%s.%s|%s|%s|%s|%s  \n" % (Pcd.TokenSpaceGuidCName, Pcd.TokenCName, str(Pcd.SkuInfoList.keys()[i]),str(Offset).strip(), str(Pcd.MaxDatumSize).strip(),PcdValue))
149                    i += 1
150        except:
151            EdkLogger.error("VpdInfoFile",
152                            BuildToolError.FILE_WRITE_FAILURE,
153                            "Fail to write file %s" % FilePath)
154        fd.close()
155
156    ## Read an existing VPD PCD info file.
157    #
158    #  This routine will read VPD PCD information from existing file and construct
159    #  internal PcdClassObject array.
160    #  This routine could be used by third-party tool to parse VPD info file content.
161    #
162    #  @param FilePath The full path string for existing VPD PCD info file.
163    def Read(self, FilePath):
164        try:
165            fd = open(FilePath, "r")
166        except:
167            EdkLogger.error("VpdInfoFile",
168                            BuildToolError.FILE_OPEN_FAILURE,
169                            "Fail to open file %s for written." % FilePath)
170        Lines = fd.readlines()
171        for Line in Lines:
172            Line = Line.strip()
173            if len(Line) == 0 or Line.startswith("#"):
174                continue
175
176            #
177            # the line must follow output format defined in BPDG spec.
178            #
179            try:
180                PcdName, SkuId,Offset, Size, Value = Line.split("#")[0].split("|")
181                PcdName, SkuId,Offset, Size, Value = PcdName.strip(), SkuId.strip(),Offset.strip(), Size.strip(), Value.strip()
182                TokenSpaceName, PcdTokenName = PcdName.split(".")
183            except:
184                EdkLogger.error("BPDG", BuildToolError.PARSER_ERROR, "Fail to parse VPD information file %s" % FilePath)
185
186            Found = False
187
188            for VpdObject in self._VpdArray.keys():
189                for sku in VpdObject.SkuInfoList.keys():
190                    if VpdObject.TokenSpaceGuidCName == TokenSpaceName and VpdObject.TokenCName == PcdTokenName.strip() and sku == SkuId:
191                        if self._VpdArray[VpdObject][VpdObject.SkuInfoList.keys().index(sku)] == "*":
192                            if Offset == "*":
193                                EdkLogger.error("BPDG", BuildToolError.FORMAT_INVALID, "The offset of %s has not been fixed up by third-party BPDG tool." % PcdName)
194                            self._VpdArray[VpdObject][VpdObject.SkuInfoList.keys().index(sku)] = Offset
195                        Found = True
196            if not Found:
197                EdkLogger.error("BPDG", BuildToolError.PARSER_ERROR, "Can not find PCD defined in VPD guid file.")
198
199    ## Get count of VPD PCD collected from platform's autogen when building.
200    #
201    #  @return The integer count value
202    def GetCount(self):
203        Count = 0
204        for OffsetList in self._VpdArray.values():
205            Count += len(OffsetList)
206
207        return Count
208
209    ## Get an offset value for a given VPD PCD
210    #
211    #  Because BPDG only support one Sku, so only return offset for SKU default.
212    #
213    #  @param vpd    A given VPD PCD
214    def GetOffset(self, vpd):
215        if not self._VpdArray.has_key(vpd):
216            return None
217
218        if len(self._VpdArray[vpd]) == 0:
219            return None
220
221        return self._VpdArray[vpd]
222
223## Call external BPDG tool to process VPD file
224#
225#  @param ToolPath      The string path name for BPDG tool
226#  @param VpdFileName   The string path name for VPD information guid.txt
227#
228def CallExtenalBPDGTool(ToolPath, VpdFileName):
229    assert ToolPath != None, "Invalid parameter ToolPath"
230    assert VpdFileName != None and os.path.exists(VpdFileName), "Invalid parameter VpdFileName"
231
232    OutputDir = os.path.dirname(VpdFileName)
233    FileName = os.path.basename(VpdFileName)
234    BaseName, ext = os.path.splitext(FileName)
235    OutputMapFileName = os.path.join(OutputDir, "%s.map" % BaseName)
236    OutputBinFileName = os.path.join(OutputDir, "%s.bin" % BaseName)
237
238    try:
239        PopenObject = subprocess.Popen([ToolPath,
240                                        '-o', OutputBinFileName,
241                                        '-m', OutputMapFileName,
242                                        '-q',
243                                        '-f',
244                                        VpdFileName],
245                                        stdout=subprocess.PIPE,
246                                        stderr= subprocess.PIPE)
247    except Exception, X:
248        EdkLogger.error("BPDG", BuildToolError.COMMAND_FAILURE, ExtraData="%s" % (str(X)))
249    (out, error) = PopenObject.communicate()
250    print out
251    while PopenObject.returncode == None :
252        PopenObject.wait()
253
254    if PopenObject.returncode != 0:
255        if PopenObject.returncode != 0:
256            EdkLogger.debug(EdkLogger.DEBUG_1, "Fail to call BPDG tool", str(error))
257            EdkLogger.error("BPDG", BuildToolError.COMMAND_FAILURE, "Fail to execute BPDG tool with exit code: %d, the error message is: \n %s" % \
258                            (PopenObject.returncode, str(error)))
259
260    return PopenObject.returncode
261