wafsamba/samba_autoconf: when setting undefined result, use empty tuple
[samba.git] / buildtools / wafsamba / samba_abi.py
1 # functions for handling ABI checking of libraries
2
3 import os
4 import sys
5 import re
6 import fnmatch
7
8 from waflib import Options, Utils, Logs, Task, Build, Errors
9 from waflib.TaskGen import feature, before, after
10 import samba_utils
11
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'
17     }
18
19 version_key = lambda x: map(int, x.split("."))
20
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)
29
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
40
41
42 def normalise_varargs(sig):
43     '''cope with older versions of gdb'''
44     sig = re.sub(',\s\.\.\.', '', sig)
45     return sig
46
47
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
72
73 def save_sigs(sig_file, parsed_sigs):
74     '''save ABI signatures to a file'''
75     sigs = ''
76     for s in sorted(parsed_sigs.keys()):
77         sigs += '%s: %s\n' % (s, parsed_sigs[s])
78     return samba_utils.save_file(sig_file, sigs, create_dir=True)
79
80
81 def abi_check_task(self):
82     '''check if the ABI has changed'''
83     abi_gen = self.ABI_GEN
84
85     libpath = self.inputs[0].abspath(self.env)
86     libname = os.path.basename(libpath)
87
88     sigs = Utils.cmd_output([abi_gen, libpath])
89     parsed_sigs = parse_sigs(sigs, self.ABI_MATCH)
90
91     sig_file = self.ABI_FILE
92
93     old_sigs = samba_utils.load_file(sig_file)
94     if old_sigs is None or Options.options.ABI_UPDATE:
95         if not save_sigs(sig_file, parsed_sigs):
96             raise Errors.WafError('Failed to save ABI file "%s"' % sig_file)
97         Logs.warn('Generated ABI signatures %s' % sig_file)
98         return
99
100     parsed_old_sigs = parse_sigs(old_sigs, self.ABI_MATCH)
101
102     # check all old sigs
103     got_error = False
104     for s in parsed_old_sigs:
105         if not s in parsed_sigs:
106             Logs.error('%s: symbol %s has been removed - please update major version\n\tsignature: %s' % (
107                 libname, s, parsed_old_sigs[s]))
108             got_error = True
109         elif normalise_varargs(parsed_old_sigs[s]) != normalise_varargs(parsed_sigs[s]):
110             Logs.error('%s: symbol %s has changed - please update major version\n\told_signature: %s\n\tnew_signature: %s' % (
111                 libname, s, parsed_old_sigs[s], parsed_sigs[s]))
112             got_error = True
113
114     for s in parsed_sigs:
115         if not s in parsed_old_sigs:
116             Logs.error('%s: symbol %s has been added - please mark it _PRIVATE_ or update minor version\n\tsignature: %s' % (
117                 libname, s, parsed_sigs[s]))
118             got_error = True
119
120     if got_error:
121         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
123
124 t = Task.task_factory('abi_check', abi_check_task, color='BLUE', ext_in='.bin')
125 t.quiet = True
126 # allow "waf --abi-check" to force re-checking the ABI
127 if '--abi-check' in sys.argv:
128     t.always_run = True
129
130 @after('apply_link')
131 @feature('abi_check')
132 def abi_check(self):
133     '''check that ABI matches saved signatures'''
134     env = self.bld.env
135     if not env.ABI_CHECK or self.abi_directory is None:
136         return
137
138     # if the platform doesn't support -fvisibility=hidden then the ABI
139     # checks become fairly meaningless
140     if not env.HAVE_VISIBILITY_ATTR:
141         return
142
143     topsrc = self.bld.srcnode.abspath()
144     abi_gen = os.path.join(topsrc, 'buildtools/scripts/abi_gen.sh')
145
146     abi_file = "%s/%s-%s.sigs" % (self.abi_directory, self.version_libname,
147                                   self.vnum)
148
149     tsk = self.create_task('abi_check', self.link_task.outputs[0])
150     tsk.ABI_FILE = abi_file
151     tsk.ABI_MATCH = self.abi_match
152     tsk.ABI_GEN = abi_gen
153
154
155 def abi_process_file(fname, version, symmap):
156     '''process one ABI file, adding new symbols to the symmap'''
157     for line in Utils.readf(fname).splitlines():
158         symname = line.split(":")[0]
159         if not symname in symmap:
160             symmap[symname] = version
161
162
163 def abi_write_vscript(f, libname, current_version, versions, symmap, abi_match):
164     """Write a vscript file for a library in --version-script format.
165
166     :param f: File-like object to write to
167     :param libname: Name of the library, uppercased
168     :param current_version: Current version
169     :param versions: Versions to consider
170     :param symmap: Dictionary mapping symbols -> version
171     :param abi_match: List of symbols considered to be public in the current
172         version
173     """
174
175     invmap = {}
176     for s in symmap:
177         invmap.setdefault(symmap[s], []).append(s)
178
179     last_key = ""
180     versions = sorted(versions, key=version_key)
181     for k in versions:
182         symver = "%s_%s" % (libname, k)
183         if symver == current_version:
184             break
185         f.write("%s {\n" % symver)
186         if k in sorted(invmap.keys()):
187             f.write("\tglobal:\n")
188             for s in invmap.get(k, []):
189                 f.write("\t\t%s;\n" % s);
190         f.write("}%s;\n\n" % last_key)
191         last_key = " %s" % symver
192     f.write("%s {\n" % current_version)
193     local_abi = filter(lambda x: x[0] == '!', abi_match)
194     global_abi = filter(lambda x: x[0] != '!', abi_match)
195     f.write("\tglobal:\n")
196     if len(global_abi) > 0:
197         for x in global_abi:
198             f.write("\t\t%s;\n" % x)
199     else:
200         f.write("\t\t*;\n")
201     # Always hide symbols that must be local if exist
202     local_abi.extend(["!_end", "!__bss_start", "!_edata"])
203     f.write("\tlocal:\n")
204     for x in local_abi:
205         f.write("\t\t%s;\n" % x[1:])
206     if global_abi != ["*"]:
207         if len(global_abi) > 0:
208             f.write("\t\t*;\n")
209     f.write("};\n")
210
211
212 def abi_build_vscript(task):
213     '''generate a vscript file for our public libraries'''
214
215     tgt = task.outputs[0].bldpath(task.env)
216
217     symmap = {}
218     versions = []
219     for f in task.inputs:
220         fname = f.abspath(task.env)
221         basename = os.path.basename(fname)
222         version = basename[len(task.env.LIBNAME)+1:-len(".sigs")]
223         versions.append(version)
224         abi_process_file(fname, version, symmap)
225     f = open(tgt, mode='w')
226     try:
227         abi_write_vscript(f, task.env.LIBNAME, task.env.VERSION, versions,
228             symmap, task.env.ABI_MATCH)
229     finally:
230         f.close()
231
232
233 def ABI_VSCRIPT(bld, libname, abi_directory, version, vscript, abi_match=None):
234     '''generate a vscript file for our public libraries'''
235     if abi_directory:
236         source = bld.path.ant_glob('%s/%s-[0-9]*.sigs' % (abi_directory, libname), flat=True)
237         def abi_file_key(path):
238             return version_key(path[:-len(".sigs")].rsplit("-")[-1])
239         source = sorted(source.split(), key=abi_file_key)
240     else:
241         source = ''
242
243     libname = os.path.basename(libname)
244     version = os.path.basename(version)
245     libname = libname.replace("-", "_").replace("+","_").upper()
246     version = version.replace("-", "_").replace("+","_").upper()
247
248     t = bld.SAMBA_GENERATOR(vscript,
249                             rule=abi_build_vscript,
250                             source=source,
251                             group='vscripts',
252                             target=vscript)
253     if abi_match is None:
254         abi_match = ["*"]
255     else:
256         abi_match = samba_utils.TO_LIST(abi_match)
257     t.env.ABI_MATCH = abi_match
258     t.env.VERSION = version
259     t.env.LIBNAME = libname
260     t.vars = ['LIBNAME', 'VERSION', 'ABI_MATCH']
261 Build.BuildContext.ABI_VSCRIPT = ABI_VSCRIPT