Maintainers.txt: Update email address
[mirror_edk2.git] / BaseTools / Source / Python / GenPatchPcdTable / GenPatchPcdTable.py
1 ## @file
2 # Generate PCD table for 'Patchable In Module' type PCD with given .map file.
3 # The Patch PCD table like:
4 #
5 # PCD Name Offset in binary
6 # ======== ================
7 #
8 # Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.<BR>
9 # SPDX-License-Identifier: BSD-2-Clause-Patent
10 #
11 #
12
13 #====================================== External Libraries ========================================
14 from __future__ import print_function
15 import optparse
16 import Common.LongFilePathOs as os
17 import re
18 import array
19
20 from Common.BuildToolError import *
21 import Common.EdkLogger as EdkLogger
22 from Common.Misc import PeImageClass, startPatternGeneral, addressPatternGeneral, valuePatternGcc, pcdPatternGcc, secReGeneral
23 from Common.BuildVersion import gBUILD_VERSION
24 from Common.LongFilePathSupport import OpenLongFilePath as open
25
26 # Version and Copyright
27 __version_number__ = ("0.10" + " " + gBUILD_VERSION)
28 __version__ = "%prog Version " + __version_number__
29 __copyright__ = "Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved."
30
31 #====================================== Internal Libraries ========================================
32
33 #============================================== Code ===============================================
34 symRe = re.compile('^([\da-fA-F]+):([\da-fA-F]+) +([\.\-:\\\\\w\?@\$<>]+) +([\da-fA-F]+)', re.UNICODE)
35
36 def parsePcdInfoFromMapFile(mapfilepath, efifilepath):
37 """ Parse map file to get binary patch pcd information
38 @param path Map file absolution path
39
40 @return a list which element hold (PcdName, Offset, SectionName)
41 """
42 lines = []
43 try:
44 f = open(mapfilepath, 'r')
45 lines = f.readlines()
46 f.close()
47 except:
48 return None
49
50 if len(lines) == 0: return None
51 firstline = lines[0].strip()
52 if re.match('^\s*Address\s*Size\s*Align\s*Out\s*In\s*Symbol\s*$', firstline):
53 return _parseForXcodeAndClang9(lines, efifilepath)
54 if (firstline.startswith("Archive member included ") and
55 firstline.endswith(" file (symbol)")):
56 return _parseForGCC(lines, efifilepath)
57 if firstline.startswith("# Path:"):
58 return _parseForXcodeAndClang9(lines, efifilepath)
59 return _parseGeneral(lines, efifilepath)
60
61 def _parseForXcodeAndClang9(lines, efifilepath):
62 valuePattern = re.compile('^([\da-fA-FxX]+)([\s\S]*)([_]*_gPcd_BinaryPatch_([\w]+))')
63 status = 0
64 pcds = []
65 for line in lines:
66 line = line.strip()
67 if status == 0 and (re.match('^\s*Address\s*Size\s*Align\s*Out\s*In\s*Symbol\s*$', line) \
68 or line == "# Symbols:"):
69 status = 1
70 continue
71 if status == 1 and len(line) != 0:
72 if '_gPcd_BinaryPatch_' in line:
73 m = valuePattern.match(line)
74 if m is not None:
75 pcds.append((m.groups(0)[3], int(m.groups(0)[0], 16)))
76 return pcds
77
78 def _parseForGCC(lines, efifilepath):
79 """ Parse map file generated by GCC linker """
80 dataPattern = re.compile('^.data._gPcd_BinaryPatch_([\w_\d]+)$')
81 status = 0
82 imageBase = -1
83 sections = []
84 bpcds = []
85 for index, line in enumerate(lines):
86 line = line.strip()
87 # status machine transection
88 if status == 0 and line == "Memory Configuration":
89 status = 1
90 continue
91 elif status == 1 and line == 'Linker script and memory map':
92 status = 2
93 continue
94 elif status ==2 and line == 'START GROUP':
95 status = 3
96 continue
97
98 # status handler
99 if status == 3:
100 m = valuePatternGcc.match(line)
101 if m is not None:
102 sections.append(m.groups(0))
103 if status == 3:
104 m = dataPattern.match(line)
105 if m is not None:
106 if lines[index + 1]:
107 PcdName = m.groups(0)[0]
108 m = pcdPatternGcc.match(lines[index + 1].strip())
109 if m is not None:
110 bpcds.append((PcdName, int(m.groups(0)[0], 16), int(sections[-1][1], 16), sections[-1][0]))
111
112 # get section information from efi file
113 efisecs = PeImageClass(efifilepath).SectionHeaderList
114 if efisecs is None or len(efisecs) == 0:
115 return None
116 #redirection
117 redirection = 0
118 for efisec in efisecs:
119 for section in sections:
120 if section[0].strip() == efisec[0].strip() and section[0].strip() == '.text':
121 redirection = int(section[1], 16) - efisec[1]
122 pcds = []
123 for pcd in bpcds:
124 for efisec in efisecs:
125 if pcd[1] >= efisec[1] and pcd[1] < efisec[1]+efisec[3]:
126 #assert efisec[0].strip() == pcd[3].strip() and efisec[1] + redirection == pcd[2], "There are some differences between map file and efi file"
127 pcds.append([pcd[0], efisec[2] + pcd[1] - efisec[1] - redirection, efisec[0]])
128 return pcds
129
130 def _parseGeneral(lines, efifilepath):
131 """ For MSFT, ICC, EBC
132 @param lines line array for map file
133
134 @return a list which element hold (PcdName, Offset, SectionName)
135 """
136 status = 0 #0 - beginning of file; 1 - PE section definition; 2 - symbol table
137 secs = [] # key = section name
138 bPcds = []
139 symPattern = re.compile('^[_]+gPcd_BinaryPatch_([\w]+)')
140
141 for line in lines:
142 line = line.strip()
143 if startPatternGeneral.match(line):
144 status = 1
145 continue
146 if addressPatternGeneral.match(line):
147 status = 2
148 continue
149 if line.startswith("entry point at"):
150 status = 3
151 continue
152 if status == 1 and len(line) != 0:
153 m = secReGeneral.match(line)
154 assert m is not None, "Fail to parse the section in map file , line is %s" % line
155 sec_no, sec_start, sec_length, sec_name, sec_class = m.groups(0)
156 secs.append([int(sec_no, 16), int(sec_start, 16), int(sec_length, 16), sec_name, sec_class])
157 if status == 2 and len(line) != 0:
158 m = symRe.match(line)
159 assert m is not None, "Fail to parse the symbol in map file, line is %s" % line
160 sec_no, sym_offset, sym_name, vir_addr = m.groups(0)
161 sec_no = int(sec_no, 16)
162 sym_offset = int(sym_offset, 16)
163 vir_addr = int(vir_addr, 16)
164 m2 = symPattern.match(sym_name)
165 if m2 is not None:
166 # fond a binary pcd entry in map file
167 for sec in secs:
168 if sec[0] == sec_no and (sym_offset >= sec[1] and sym_offset < sec[1] + sec[2]):
169 bPcds.append([m2.groups(0)[0], sec[3], sym_offset, vir_addr, sec_no])
170
171 if len(bPcds) == 0: return None
172
173 # get section information from efi file
174 efisecs = PeImageClass(efifilepath).SectionHeaderList
175 if efisecs is None or len(efisecs) == 0:
176 return None
177
178 pcds = []
179 for pcd in bPcds:
180 index = 0
181 for efisec in efisecs:
182 index = index + 1
183 if pcd[1].strip() == efisec[0].strip():
184 pcds.append([pcd[0], efisec[2] + pcd[2], efisec[0]])
185 elif pcd[4] == index:
186 pcds.append([pcd[0], efisec[2] + pcd[2], efisec[0]])
187 return pcds
188
189 def generatePcdTable(list, pcdpath):
190 try:
191 f = open(pcdpath, 'w')
192 except:
193 pass
194
195 f.write('PCD Name Offset Section Name\r\n')
196
197 for pcditem in list:
198 f.write('%-30s 0x%-08X %-6s\r\n' % (pcditem[0], pcditem[1], pcditem[2]))
199 f.close()
200
201 #print 'Success to generate Binary Patch PCD table at %s!' % pcdpath
202
203 if __name__ == '__main__':
204 UsageString = "%prog -m <MapFile> -e <EfiFile> -o <OutFile>"
205 AdditionalNotes = "\nPCD table is generated in file name with .BinaryPcdTable.txt postfix"
206 parser = optparse.OptionParser(description=__copyright__, version=__version__, usage=UsageString)
207 parser.add_option('-m', '--mapfile', action='store', dest='mapfile',
208 help='Absolute path of module map file.')
209 parser.add_option('-e', '--efifile', action='store', dest='efifile',
210 help='Absolute path of EFI binary file.')
211 parser.add_option('-o', '--outputfile', action='store', dest='outfile',
212 help='Absolute path of output file to store the got patchable PCD table.')
213
214 (options, args) = parser.parse_args()
215
216 if options.mapfile is None or options.efifile is None:
217 print(parser.get_usage())
218 elif os.path.exists(options.mapfile) and os.path.exists(options.efifile):
219 list = parsePcdInfoFromMapFile(options.mapfile, options.efifile)
220 if list is not None:
221 if options.outfile is not None:
222 generatePcdTable(list, options.outfile)
223 else:
224 generatePcdTable(list, options.mapfile.replace('.map', '.BinaryPcdTable.txt'))
225 else:
226 print('Fail to generate Patch PCD Table based on map file and efi file')
227 else:
228 print('Fail to generate Patch PCD Table for fail to find map file or efi file!')