BaseTools: Enhance BaseTools supports FixedAtBuild usage in VFR file
[mirror_edk2.git] / BaseTools / Source / Python / PatchPcdValue / PatchPcdValue.py
CommitLineData
f51461c8
LG
1## @file\r
2# Patch value into the binary file.\r
3#\r
1be2ed90 4# Copyright (c) 2010 - 2014, Intel Corporation. All rights reserved.<BR>\r
f51461c8
LG
5# This program and the accompanying materials\r
6# are licensed and made available under the terms and conditions of the BSD License\r
7# which accompanies this distribution. The full text of the license may be found at\r
8# http://opensource.org/licenses/bsd-license.php\r
9#\r
10# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
11# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
12#\r
13\r
14##\r
15# Import Modules\r
16#\r
1be2ed90
HC
17import Common.LongFilePathOs as os\r
18from Common.LongFilePathSupport import OpenLongFilePath as open\r
f51461c8
LG
19import sys\r
20import re\r
21\r
22from optparse import OptionParser\r
23from optparse import make_option\r
24from Common.BuildToolError import *\r
25import Common.EdkLogger as EdkLogger\r
26from Common.BuildVersion import gBUILD_VERSION\r
27import array\r
28\r
29# Version and Copyright\r
30__version_number__ = ("0.10" + " " + gBUILD_VERSION)\r
31__version__ = "%prog Version " + __version_number__\r
32__copyright__ = "Copyright (c) 2010, Intel Corporation. All rights reserved."\r
33\r
34## PatchBinaryFile method\r
35#\r
36# This method mainly patches the data into binary file.\r
37# \r
38# @param FileName File path of the binary file\r
39# @param ValueOffset Offset value \r
40# @param TypeName DataType Name\r
41# @param Value Value String\r
42# @param MaxSize MaxSize value\r
43#\r
44# @retval 0 File is updated successfully.\r
45# @retval not 0 File is updated failed.\r
46#\r
47def PatchBinaryFile(FileName, ValueOffset, TypeName, ValueString, MaxSize=0):\r
48 #\r
49 # Length of Binary File\r
50 #\r
47fea6af 51 FileHandle = open(FileName, 'rb')\r
f51461c8
LG
52 FileHandle.seek (0, 2)\r
53 FileLength = FileHandle.tell()\r
54 FileHandle.close()\r
55 #\r
56 # Unify string to upper string\r
57 #\r
58 TypeName = TypeName.upper()\r
59 #\r
60 # Get PCD value data length\r
61 #\r
62 ValueLength = 0\r
63 if TypeName == 'BOOLEAN':\r
64 ValueLength = 1\r
65 elif TypeName == 'UINT8':\r
66 ValueLength = 1\r
67 elif TypeName == 'UINT16':\r
68 ValueLength = 2\r
69 elif TypeName == 'UINT32':\r
70 ValueLength = 4\r
71 elif TypeName == 'UINT64':\r
72 ValueLength = 8\r
73 elif TypeName == 'VOID*':\r
74 if MaxSize == 0:\r
75 return OPTION_MISSING, "PcdMaxSize is not specified for VOID* type PCD."\r
76 ValueLength = int(MaxSize)\r
77 else:\r
47fea6af 78 return PARAMETER_INVALID, "PCD type %s is not valid." % (CommandOptions.PcdTypeName)\r
f51461c8
LG
79 #\r
80 # Check PcdValue is in the input binary file.\r
81 #\r
82 if ValueOffset + ValueLength > FileLength:\r
83 return PARAMETER_INVALID, "PcdOffset + PcdMaxSize(DataType) is larger than the input file size."\r
84 #\r
85 # Read binary file into array\r
86 #\r
47fea6af 87 FileHandle = open(FileName, 'rb')\r
f51461c8
LG
88 ByteArray = array.array('B')\r
89 ByteArray.fromfile(FileHandle, FileLength)\r
90 FileHandle.close()\r
91 OrigByteList = ByteArray.tolist()\r
92 ByteList = ByteArray.tolist()\r
93 #\r
94 # Clear the data in file\r
95 #\r
96 for Index in range(ValueLength):\r
97 ByteList[ValueOffset + Index] = 0\r
98 #\r
99 # Patch value into offset\r
100 #\r
101 SavedStr = ValueString\r
102 ValueString = ValueString.upper()\r
103 ValueNumber = 0\r
104 if TypeName == 'BOOLEAN':\r
105 #\r
106 # Get PCD value for BOOLEAN data type\r
107 #\r
108 try:\r
109 if ValueString == 'TRUE':\r
110 ValueNumber = 1\r
111 elif ValueString == 'FALSE':\r
112 ValueNumber = 0\r
113 elif ValueString.startswith('0X'):\r
114 ValueNumber = int (ValueString, 16)\r
115 else:\r
116 ValueNumber = int (ValueString)\r
117 if ValueNumber != 0:\r
118 ValueNumber = 1\r
119 except:\r
47fea6af 120 return PARAMETER_INVALID, "PCD Value %s is not valid dec or hex string." % (ValueString)\r
f51461c8
LG
121 #\r
122 # Set PCD value into binary data\r
123 #\r
124 ByteList[ValueOffset] = ValueNumber\r
125 elif TypeName in ['UINT8', 'UINT16', 'UINT32', 'UINT64']:\r
126 #\r
127 # Get PCD value for UINT* data type\r
128 #\r
129 try:\r
130 if ValueString.startswith('0X'):\r
131 ValueNumber = int (ValueString, 16)\r
132 else:\r
133 ValueNumber = int (ValueString)\r
134 except:\r
47fea6af 135 return PARAMETER_INVALID, "PCD Value %s is not valid dec or hex string." % (ValueString)\r
f51461c8
LG
136 #\r
137 # Set PCD value into binary data\r
138 #\r
139 for Index in range(ValueLength):\r
140 ByteList[ValueOffset + Index] = ValueNumber % 0x100\r
141 ValueNumber = ValueNumber / 0x100\r
142 elif TypeName == 'VOID*':\r
143 ValueString = SavedStr\r
144 if ValueString.startswith('L"'):\r
145 #\r
146 # Patch Unicode String\r
147 #\r
148 Index = 0\r
149 for ByteString in ValueString[2:-1]:\r
150 #\r
151 # Reserve zero as unicode tail\r
152 #\r
153 if Index + 2 >= ValueLength:\r
154 break\r
155 #\r
156 # Set string value one by one\r
157 #\r
158 ByteList[ValueOffset + Index] = ord(ByteString)\r
159 Index = Index + 2\r
160 elif ValueString.startswith("{") and ValueString.endswith("}"):\r
161 #\r
162 # Patch {0x1, 0x2, ...} byte by byte\r
163 #\r
164 ValueList = ValueString[1 : len(ValueString) - 1].split(', ')\r
165 Index = 0\r
166 try:\r
167 for ByteString in ValueList:\r
168 if ByteString.upper().startswith('0X'):\r
169 ByteValue = int(ByteString, 16)\r
170 else:\r
171 ByteValue = int(ByteString)\r
172 ByteList[ValueOffset + Index] = ByteValue % 0x100\r
173 Index = Index + 1\r
174 if Index >= ValueLength:\r
175 break\r
176 except:\r
47fea6af 177 return PARAMETER_INVALID, "PCD Value %s is not valid dec or hex string array." % (ValueString)\r
f51461c8
LG
178 else:\r
179 #\r
180 # Patch ascii string \r
181 #\r
182 Index = 0\r
183 for ByteString in ValueString[1:-1]:\r
184 #\r
185 # Reserve zero as string tail\r
186 #\r
187 if Index + 1 >= ValueLength:\r
188 break\r
189 #\r
190 # Set string value one by one\r
191 #\r
192 ByteList[ValueOffset + Index] = ord(ByteString)\r
193 Index = Index + 1\r
194 #\r
195 # Update new data into input file.\r
196 #\r
197 if ByteList != OrigByteList:\r
198 ByteArray = array.array('B')\r
199 ByteArray.fromlist(ByteList)\r
47fea6af 200 FileHandle = open(FileName, 'wb')\r
f51461c8
LG
201 ByteArray.tofile(FileHandle)\r
202 FileHandle.close()\r
47fea6af 203 return 0, "Patch Value into File %s successfully." % (FileName)\r
f51461c8
LG
204\r
205## Parse command line options\r
206#\r
207# Using standard Python module optparse to parse command line option of this tool.\r
208#\r
209# @retval Options A optparse.Values object containing the parsed options\r
210# @retval InputFile Path of file to be trimmed\r
211#\r
212def Options():\r
213 OptionList = [\r
214 make_option("-f", "--offset", dest="PcdOffset", action="store", type="int",\r
215 help="Start offset to the image is used to store PCD value."),\r
216 make_option("-u", "--value", dest="PcdValue", action="store",\r
217 help="PCD value will be updated into the image."),\r
218 make_option("-t", "--type", dest="PcdTypeName", action="store",\r
219 help="The name of PCD data type may be one of VOID*,BOOLEAN, UINT8, UINT16, UINT32, UINT64."),\r
220 make_option("-s", "--maxsize", dest="PcdMaxSize", action="store", type="int",\r
221 help="Max size of data buffer is taken by PCD value.It must be set when PCD type is VOID*."),\r
222 make_option("-v", "--verbose", dest="LogLevel", action="store_const", const=EdkLogger.VERBOSE,\r
223 help="Run verbosely"),\r
224 make_option("-d", "--debug", dest="LogLevel", type="int",\r
225 help="Run with debug information"),\r
226 make_option("-q", "--quiet", dest="LogLevel", action="store_const", const=EdkLogger.QUIET,\r
227 help="Run quietly"),\r
228 make_option("-?", action="help", help="show this help message and exit"),\r
229 ]\r
230\r
231 # use clearer usage to override default usage message\r
232 UsageString = "%prog -f Offset -u Value -t Type [-s MaxSize] <input_file>"\r
233\r
234 Parser = OptionParser(description=__copyright__, version=__version__, option_list=OptionList, usage=UsageString)\r
235 Parser.set_defaults(LogLevel=EdkLogger.INFO)\r
236\r
237 Options, Args = Parser.parse_args()\r
238\r
239 # error check\r
240 if len(Args) == 0:\r
241 EdkLogger.error("PatchPcdValue", PARAMETER_INVALID, ExtraData=Parser.get_usage())\r
242\r
243 InputFile = Args[len(Args) - 1]\r
244 return Options, InputFile\r
245\r
246## Entrance method\r
247#\r
248# This method mainly dispatch specific methods per the command line options.\r
249# If no error found, return zero value so the caller of this tool can know\r
250# if it's executed successfully or not.\r
251#\r
252# @retval 0 Tool was successful\r
253# @retval 1 Tool failed\r
254#\r
255def Main():\r
256 try:\r
257 #\r
258 # Check input parameter\r
259 #\r
260 EdkLogger.Initialize()\r
261 CommandOptions, InputFile = Options()\r
262 if CommandOptions.LogLevel < EdkLogger.DEBUG_9:\r
263 EdkLogger.SetLevel(CommandOptions.LogLevel + 1)\r
264 else:\r
265 EdkLogger.SetLevel(CommandOptions.LogLevel)\r
266 if not os.path.exists (InputFile):\r
267 EdkLogger.error("PatchPcdValue", FILE_NOT_FOUND, ExtraData=InputFile)\r
268 return 1\r
269 if CommandOptions.PcdOffset == None or CommandOptions.PcdValue == None or CommandOptions.PcdTypeName == None:\r
270 EdkLogger.error("PatchPcdValue", OPTION_MISSING, ExtraData="PcdOffset or PcdValue of PcdTypeName is not specified.")\r
271 return 1\r
272 if CommandOptions.PcdTypeName.upper() not in ["BOOLEAN", "UINT8", "UINT16", "UINT32", "UINT64", "VOID*"]:\r
47fea6af 273 EdkLogger.error("PatchPcdValue", PARAMETER_INVALID, ExtraData="PCD type %s is not valid." % (CommandOptions.PcdTypeName))\r
f51461c8
LG
274 return 1\r
275 if CommandOptions.PcdTypeName.upper() == "VOID*" and CommandOptions.PcdMaxSize == None:\r
276 EdkLogger.error("PatchPcdValue", OPTION_MISSING, ExtraData="PcdMaxSize is not specified for VOID* type PCD.")\r
277 return 1\r
278 #\r
279 # Patch value into binary image.\r
280 #\r
281 ReturnValue, ErrorInfo = PatchBinaryFile (InputFile, CommandOptions.PcdOffset, CommandOptions.PcdTypeName, CommandOptions.PcdValue, CommandOptions.PcdMaxSize)\r
282 if ReturnValue != 0:\r
283 EdkLogger.error("PatchPcdValue", ReturnValue, ExtraData=ErrorInfo)\r
284 return 1\r
285 return 0\r
286 except:\r
287 return 1\r
288\r
289if __name__ == '__main__':\r
290 r = Main()\r
291 sys.exit(r)\r