s3: lib: Add new clistr_smb2_extract_snapshot_token() function.
[Samba.git] / buildtools / wafsamba / samba_abi.py
blob80643aa28d7d7a09f2cb32ce2ff1614c566c2e0e
1 # functions for handling ABI checking of libraries
3 import os
4 import sys
5 import re
6 import fnmatch
8 from waflib import Options, Utils, Logs, Task, Build, Errors
9 from waflib.TaskGen import feature, before, after
10 from wafsamba import samba_utils
12 # these type maps cope with platform specific names for common types
13 # please add new type mappings into the list below
14 abi_type_maps = {
15 '_Bool' : 'bool',
16 'struct __va_list_tag *' : 'va_list'
19 version_key = lambda x: list(map(int, x.split(".")))
21 def normalise_signature(sig):
22 '''normalise a signature from gdb'''
23 sig = sig.strip()
24 sig = re.sub('^\$[0-9]+\s=\s\{(.+)\}$', r'\1', sig)
25 sig = re.sub('^\$[0-9]+\s=\s\{(.+)\}(\s0x[0-9a-f]+\s<\w+>)+$', r'\1', sig)
26 sig = re.sub('^\$[0-9]+\s=\s(0x[0-9a-f]+)\s?(<\w+>)?$', r'\1', sig)
27 sig = re.sub('0x[0-9a-f]+', '0xXXXX', sig)
28 sig = re.sub('", <incomplete sequence (\\\\[a-z0-9]+)>', r'\1"', sig)
30 for t in abi_type_maps:
31 # we need to cope with non-word characters in mapped types
32 m = t
33 m = m.replace('*', '\*')
34 if m[-1].isalnum() or m[-1] == '_':
35 m += '\\b'
36 if m[0].isalnum() or m[0] == '_':
37 m = '\\b' + m
38 sig = re.sub(m, abi_type_maps[t], sig)
39 return sig
42 def normalise_varargs(sig):
43 '''cope with older versions of gdb'''
44 sig = re.sub(',\s\.\.\.', '', sig)
45 return sig
48 def parse_sigs(sigs, abi_match):
49 '''parse ABI signatures file'''
50 abi_match = samba_utils.TO_LIST(abi_match)
51 ret = {}
52 a = sigs.split('\n')
53 for s in a:
54 if s.find(':') == -1:
55 continue
56 sa = s.split(':')
57 if abi_match:
58 matched = False
59 negative = False
60 for p in abi_match:
61 if p[0] == '!' and fnmatch.fnmatch(sa[0], p[1:]):
62 negative = True
63 break
64 elif fnmatch.fnmatch(sa[0], p):
65 matched = True
66 break
67 if (not matched) and negative:
68 continue
69 Logs.debug("%s -> %s" % (sa[1], normalise_signature(sa[1])))
70 ret[sa[0]] = normalise_signature(sa[1])
71 return ret
73 def save_sigs(sig_file, parsed_sigs):
74 '''save ABI signatures to a file'''
75 sigs = "".join('%s: %s\n' % (s, parsed_sigs[s]) for s in sorted(parsed_sigs.keys()))
76 return samba_utils.save_file(sig_file, sigs, create_dir=True)
79 def abi_check_task(self):
80 '''check if the ABI has changed'''
81 abi_gen = self.ABI_GEN
83 libpath = self.inputs[0].abspath(self.env)
84 libname = os.path.basename(libpath)
86 sigs = samba_utils.get_string(Utils.cmd_output([abi_gen, libpath]))
87 parsed_sigs = parse_sigs(sigs, self.ABI_MATCH)
89 sig_file = self.ABI_FILE
91 old_sigs = samba_utils.load_file(sig_file)
92 if old_sigs is None or Options.options.ABI_UPDATE:
93 if not save_sigs(sig_file, parsed_sigs):
94 raise Errors.WafError('Failed to save ABI file "%s"' % sig_file)
95 Logs.warn('Generated ABI signatures %s' % sig_file)
96 return
98 parsed_old_sigs = parse_sigs(old_sigs, self.ABI_MATCH)
100 # check all old sigs
101 got_error = False
102 for s in parsed_old_sigs:
103 if not s in parsed_sigs:
104 Logs.error('%s: symbol %s has been removed - please update major version\n\tsignature: %s' % (
105 libname, s, parsed_old_sigs[s]))
106 got_error = True
107 elif normalise_varargs(parsed_old_sigs[s]) != normalise_varargs(parsed_sigs[s]):
108 Logs.error('%s: symbol %s has changed - please update major version\n\told_signature: %s\n\tnew_signature: %s' % (
109 libname, s, parsed_old_sigs[s], parsed_sigs[s]))
110 got_error = True
112 for s in parsed_sigs:
113 if not s in parsed_old_sigs:
114 Logs.error('%s: symbol %s has been added - please mark it _PRIVATE_ or update minor version\n\tsignature: %s' % (
115 libname, s, parsed_sigs[s]))
116 got_error = True
118 if got_error:
119 raise Errors.WafError('ABI for %s has changed - please fix library version then build with --abi-update\nSee http://wiki.samba.org/index.php/Waf#ABI_Checking for more information\nIf you have not changed any ABI, and your platform always gives this error, please configure with --abi-check-disable to skip this check' % libname)
122 t = Task.task_factory('abi_check', abi_check_task, color='BLUE', ext_in='.bin')
123 t.quiet = True
124 # allow "waf --abi-check" to force re-checking the ABI
125 if '--abi-check' in sys.argv:
126 t.always_run = True
128 @after('apply_link')
129 @feature('abi_check')
130 def abi_check(self):
131 '''check that ABI matches saved signatures'''
132 env = self.bld.env
133 if not env.ABI_CHECK or self.abi_directory is None:
134 return
136 # if the platform doesn't support -fvisibility=hidden then the ABI
137 # checks become fairly meaningless
138 if not env.HAVE_VISIBILITY_ATTR:
139 return
141 topsrc = self.bld.srcnode.abspath()
142 abi_gen = os.path.join(topsrc, 'buildtools/scripts/abi_gen.sh')
144 abi_file = "%s/%s-%s.sigs" % (self.abi_directory, self.version_libname,
145 self.abi_vnum)
147 tsk = self.create_task('abi_check', self.link_task.outputs[0])
148 tsk.ABI_FILE = abi_file
149 tsk.ABI_MATCH = self.abi_match
150 tsk.ABI_GEN = abi_gen
153 def abi_process_file(fname, version, symmap):
154 '''process one ABI file, adding new symbols to the symmap'''
155 for line in Utils.readf(fname).splitlines():
156 symname = line.split(":")[0]
157 if not symname in symmap:
158 symmap[symname] = version
160 def version_script_map_process_file(fname, version, abi_match):
161 '''process one standard version_script file, adding the symbols to the
162 abi_match'''
163 in_section = False
164 in_global = False
165 in_local = False
166 for _line in Utils.readf(fname).splitlines():
167 line = _line.strip()
168 if line == "":
169 continue
170 if line.startswith("#"):
171 continue
172 if line.endswith(" {"):
173 in_section = True
174 continue
175 if line == "};":
176 assert in_section
177 in_section = False
178 in_global = False
179 in_local = False
180 continue
181 if not in_section:
182 continue
183 if line == "global:":
184 in_global = True
185 in_local = False
186 continue
187 if line == "local:":
188 in_global = False
189 in_local = True
190 continue
192 symname = line.split(";")[0]
193 assert symname != ""
194 if in_local:
195 if symname == "*":
196 continue
197 symname = "!%s" % symname
198 if not symname in abi_match:
199 abi_match.append(symname)
201 def abi_write_vscript(f, libname, current_version, versions, symmap, abi_match):
202 """Write a vscript file for a library in --version-script format.
204 :param f: File-like object to write to
205 :param libname: Name of the library, uppercased
206 :param current_version: Current version
207 :param versions: Versions to consider
208 :param symmap: Dictionary mapping symbols -> version
209 :param abi_match: List of symbols considered to be public in the current
210 version
213 invmap = {}
214 for s in symmap:
215 invmap.setdefault(symmap[s], []).append(s)
217 last_key = ""
218 versions = sorted(versions, key=version_key)
219 for k in versions:
220 symver = "%s_%s" % (libname, k)
221 if symver == current_version:
222 break
223 f.write("%s {\n" % symver)
224 if k in sorted(invmap.keys()):
225 f.write("\tglobal:\n")
226 for s in invmap.get(k, []):
227 f.write("\t\t%s;\n" % s);
228 f.write("}%s;\n\n" % last_key)
229 last_key = " %s" % symver
230 f.write("%s {\n" % current_version)
231 local_abi = list(filter(lambda x: x[0] == '!', abi_match))
232 global_abi = list(filter(lambda x: x[0] != '!', abi_match))
233 f.write("\tglobal:\n")
234 if len(global_abi) > 0:
235 for x in global_abi:
236 f.write("\t\t%s;\n" % x)
237 else:
238 f.write("\t\t*;\n")
239 # Always hide symbols that must be local if exist
240 local_abi.extend(["!_end", "!__bss_start", "!_edata"])
241 f.write("\tlocal:\n")
242 for x in local_abi:
243 f.write("\t\t%s;\n" % x[1:])
244 if global_abi != ["*"]:
245 if len(global_abi) > 0:
246 f.write("\t\t*;\n")
247 f.write("};\n")
250 def abi_build_vscript(task):
251 '''generate a vscript file for our public libraries'''
253 tgt = task.outputs[0].bldpath(task.env)
255 symmap = {}
256 versions = []
257 abi_match = list(task.env.ABI_MATCH)
258 for f in task.inputs:
259 fname = f.abspath(task.env)
260 basename = os.path.basename(fname)
261 if basename.endswith(".sigs"):
262 version = basename[len(task.env.LIBNAME)+1:-len(".sigs")]
263 versions.append(version)
264 abi_process_file(fname, version, symmap)
265 continue
266 if basename == "version-script.map":
267 version_script_map_process_file(fname, task.env.VERSION, abi_match)
268 continue
269 raise Errors.WafError('Unsupported input "%s"' % fname)
270 if task.env.PRIVATE_LIBRARY:
271 # For private libraries we need to inject
272 # each public symbol explicitly into the
273 # abi match array and remove all explicit
274 # versioning so that each exported symbol
275 # is tagged with the private library tag.
276 for s in symmap:
277 abi_match.append(s)
278 symmap = {}
279 versions = []
280 f = open(tgt, mode='w')
281 try:
282 abi_write_vscript(f, task.env.LIBNAME, task.env.VERSION, versions,
283 symmap, abi_match)
284 finally:
285 f.close()
287 def VSCRIPT_MAP_PRIVATE(bld, libname, orig_vscript, version, private_vscript):
288 version = version.replace("-", "_").replace("+","_").upper()
289 t = bld.SAMBA_GENERATOR(private_vscript,
290 rule=abi_build_vscript,
291 source=orig_vscript,
292 group='vscripts',
293 target=private_vscript)
294 t.env.ABI_MATCH = []
295 t.env.VERSION = version
296 t.env.LIBNAME = libname
297 t.env.PRIVATE_LIBRARY = True
298 t.vars = ['LIBNAME', 'VERSION', 'ABI_MATCH', 'PRIVATE_LIBRARY']
299 Build.BuildContext.VSCRIPT_MAP_PRIVATE = VSCRIPT_MAP_PRIVATE
301 def ABI_VSCRIPT(bld, libname, abi_directory, version, vscript, abi_match=None, private_library=False):
302 '''generate a vscript file for our public libraries'''
303 if abi_directory:
304 source = bld.path.ant_glob('%s/%s-[0-9]*.sigs' % (abi_directory, libname), flat=True)
305 def abi_file_key(path):
306 return version_key(path[:-len(".sigs")].rsplit("-")[-1])
307 source = sorted(source.split(), key=abi_file_key)
308 else:
309 source = ''
311 if private_library is None:
312 private_library = False
314 libname = os.path.basename(libname)
315 version = os.path.basename(version)
316 libname = libname.replace("-", "_").replace("+","_").upper()
317 version = version.replace("-", "_").replace("+","_").upper()
319 t = bld.SAMBA_GENERATOR(vscript,
320 rule=abi_build_vscript,
321 source=source,
322 group='vscripts',
323 target=vscript)
324 if abi_match is None:
325 abi_match = ["*"]
326 else:
327 abi_match = samba_utils.TO_LIST(abi_match)
328 t.env.ABI_MATCH = abi_match
329 t.env.VERSION = version
330 t.env.LIBNAME = libname
331 t.env.PRIVATE_LIBRARY = private_library
332 t.vars = ['LIBNAME', 'VERSION', 'ABI_MATCH', 'PRIVATE_LIBRARY']
333 Build.BuildContext.ABI_VSCRIPT = ABI_VSCRIPT