942748507792a17be0e46da55ff5acfb1303143a
[samba.git] / buildtools / wafsamba / symbols.py
1 # a waf tool to extract symbols from object files or libraries
2 # using nm, producing a set of exposed defined/undefined symbols
3
4 import Utils, Build, subprocess, Logs
5 from samba_wildcard import fake_build_environment
6 from samba_utils import *
7
8 # these are the data structures used in symbols.py:
9 #
10 # bld.env.symbol_map : dictionary mapping public symbol names to list of
11 #                      subsystem names where that symbol exists
12 #
13 # t.in_library       : list of libraries that t is in
14 #
15 # bld.env.public_symbols: set of public symbols for each subsystem
16 # bld.env.used_symbols  : set of used symbols for each subsystem
17 #
18 # bld.env.syslib_symbols: dictionary mapping system library name to set of symbols
19 #                         for that library
20 #
21 # LOCAL_CACHE(bld, 'TARGET_TYPE') : dictionary mapping subsystem name to target type
22
23 def symbols_extract(objfiles, dynamic=False):
24     '''extract symbols from objfile, returning a dictionary containing
25        the set of undefined and public symbols for each file'''
26
27     ret = {}
28
29     cmd = ["nm"]
30     if dynamic:
31         # needed for some .so files
32         cmd.append("-D")
33     cmd.extend(objfiles)
34
35     nmpipe = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout
36     if len(objfiles) == 1:
37         filename = objfiles[0]
38         ret[filename] = { "PUBLIC": set(), "UNDEFINED" : set()}
39
40     for line in nmpipe:
41         line = line.strip()
42         if line.endswith(':'):
43             filename = line[:-1]
44             ret[filename] = { "PUBLIC": set(), "UNDEFINED" : set() }
45             continue
46         cols = line.split(" ")
47         if cols == ['']:
48             continue
49         # see if the line starts with an address
50         if len(cols) == 3:
51             symbol_type = cols[1]
52             symbol = cols[2]
53         else:
54             symbol_type = cols[0]
55             symbol = cols[1]
56         if symbol_type in "BDGTRVWSi":
57             # its a public symbol
58             ret[filename]["PUBLIC"].add(symbol)
59         elif symbol_type in "U":
60             ret[filename]["UNDEFINED"].add(symbol)
61
62     return ret
63
64
65 def real_name(name):
66     if name.find(".objlist") != -1:
67         name = name[:-8]
68     return name
69
70
71 def find_syslib_path(bld, libname, deps):
72     '''find the path to the syslib we will link against'''
73     # the strategy is to use the targets that depend on the library, and run ldd
74     # on it to find the real location of the library that is used
75
76     linkpath = deps[0].link_task.outputs[0].abspath(bld.env)
77
78     if libname == "python":
79         libname += bld.env.PYTHON_VERSION
80
81     ret = None
82
83     lddpipe = subprocess.Popen(['ldd', linkpath], stdout=subprocess.PIPE).stdout
84     for line in lddpipe:
85         line = line.strip()
86         cols = line.split(" ")
87         if len(cols) < 3 or cols[1] != "=>":
88             continue
89         if cols[0].startswith("lib%s." % libname.lower()):
90             ret = cols[2]
91         if cols[0].startswith("libc."):
92             # save this one too
93             bld.env.libc_path = cols[2]
94     return ret
95
96
97 def build_symbol_sets(bld, tgt_list):
98     '''build the public_symbols and undefined_symbols attributes for each target'''
99
100     objlist = []  # list of object file
101     objmap = {}   # map from object filename to target (subsystem) name
102
103
104     for t in tgt_list:
105         t.public_symbols = set()
106         t.undefined_symbols = set()
107         t.used_symbols = set()
108         for tsk in getattr(t, 'compiled_tasks', []):
109             for output in tsk.outputs:
110                 objpath = output.abspath(bld.env)
111                 objlist.append(objpath)
112                 objmap[objpath] = t
113
114     symbols = symbols_extract(objlist)
115     for obj in objlist:
116         t = objmap[obj]
117         t.public_symbols = t.public_symbols.union(symbols[obj]["PUBLIC"])
118         t.undefined_symbols = t.undefined_symbols.union(symbols[obj]["UNDEFINED"])
119         t.used_symbols = t.used_symbols.union(symbols[obj]["UNDEFINED"])
120
121     t.undefined_symbols = t.undefined_symbols.difference(t.public_symbols)
122
123     # and the reverse map of public symbols to subsystem name
124     bld.env.symbol_map = {}
125
126     for t in tgt_list:
127         for s in t.public_symbols:
128             if not s in bld.env.symbol_map:
129                 bld.env.symbol_map[s] = []
130             bld.env.symbol_map[s].append(real_name(t.sname))
131
132     targets = LOCAL_CACHE(bld, 'TARGET_TYPE')
133
134     bld.env.public_symbols = {}
135     for t in tgt_list:
136         name = real_name(t.sname)
137         if name in bld.env.public_symbols:
138             bld.env.public_symbols[name] = bld.env.public_symbols[name].union(t.public_symbols)
139         else:
140             bld.env.public_symbols[name] = t.public_symbols
141         if t.samba_type == 'LIBRARY':
142             for dep in t.add_objects:
143                 t2 = bld.name_to_obj(dep, bld.env)
144                 bld.ASSERT(t2 is not None, "Library '%s' has unknown dependency '%s'" % (name, dep))
145                 bld.env.public_symbols[name] = bld.env.public_symbols[name].union(t2.public_symbols)
146
147     bld.env.used_symbols = {}
148     for t in tgt_list:
149         name = real_name(t.sname)
150         if name in bld.env.used_symbols:
151             bld.env.used_symbols[name] = bld.env.used_symbols[name].union(t.used_symbols)
152         else:
153             bld.env.used_symbols[name] = t.used_symbols
154         if t.samba_type == 'LIBRARY':
155             for dep in t.add_objects:
156                 t2 = bld.name_to_obj(dep, bld.env)
157                 bld.ASSERT(t2 is not None, "Library '%s' has unknown dependency '%s'" % (name, dep))
158                 bld.env.used_symbols[name] = bld.env.used_symbols[name].union(t2.used_symbols)
159
160
161 def build_syslib_sets(bld, tgt_list):
162     '''build the public_symbols for all syslibs'''
163
164     # work out what syslibs we depend on, and what targets those are used in
165     syslibs = {}
166     objmap = {}
167     for t in tgt_list:
168         if getattr(t, 'uselib', []) and t.samba_type in [ 'LIBRARY', 'BINARY', 'PYTHON' ]:
169             for lib in t.uselib:
170                 if lib in ['PYEMBED', 'PYEXT']:
171                     lib = "python"
172                 if not lib in syslibs:
173                     syslibs[lib] = []
174                 syslibs[lib].append(t)
175
176     # work out the paths to each syslib
177     syslib_paths = []
178     for lib in syslibs:
179         path = find_syslib_path(bld, lib, syslibs[lib])
180         if path is None:
181             Logs.warn("Unable to find syslib path for %s" % lib)
182         if path is not None:
183             syslib_paths.append(path)
184             objmap[path] = lib.lower()
185
186     # add in libc
187     syslib_paths.append(bld.env.libc_path)
188     objmap[bld.env.libc_path] = 'c'
189
190     symbols = symbols_extract(syslib_paths, dynamic=True)
191
192     # keep a map of syslib names to public symbols
193     bld.env.syslib_symbols = {}
194     for lib in symbols:
195         bld.env.syslib_symbols[lib] = symbols[lib]["PUBLIC"]
196
197     # add to the map of symbols to dependencies
198     for lib in symbols:
199         for sym in symbols[lib]["PUBLIC"]:
200             if not sym in bld.env.symbol_map:
201                 bld.env.symbol_map[sym] = []
202             bld.env.symbol_map[sym].append(objmap[lib])
203
204     # keep the libc symbols as well, as these are useful for some of the
205     # sanity checks
206     bld.env.libc_symbols = symbols[bld.env.libc_path]["PUBLIC"]
207
208     # add to the combined map of dependency name to public_symbols
209     for lib in bld.env.syslib_symbols:
210         bld.env.public_symbols[objmap[lib]] = bld.env.syslib_symbols[lib]
211
212 def build_autodeps(bld, t):
213     '''build the set of dependencies for a target'''
214     deps = set()
215     name = real_name(t.sname)
216
217     targets    = LOCAL_CACHE(bld, 'TARGET_TYPE')
218
219     for sym in t.undefined_symbols:
220         if sym in t.public_symbols:
221             continue
222         if sym in bld.env.symbol_map:
223             depname = bld.env.symbol_map[sym]
224             if depname == [ name ]:
225                 # self dependencies aren't interesting
226                 continue
227             if t.in_library == depname:
228                 # no need to depend on the library we are part of
229                 continue
230             if depname[0] in ['c', 'python']:
231                 # these don't go into autodeps
232                 continue
233             if targets[depname[0]] in [ 'SYSLIB' ]:
234                 deps.add(depname[0])
235                 continue
236             t2 = bld.name_to_obj(depname[0], bld.env)
237             if len(t2.in_library) != 1:
238                 deps.add(depname[0])
239                 continue
240             if t2.in_library == t.in_library:
241                 # if we're part of the same library, we don't need to autodep
242                 continue
243             deps.add(t2.in_library[0])
244     t.autodeps = deps
245
246
247 def build_library_names(bld, tgt_list):
248     '''add a in_library attribute to all targets that are part of a library'''
249     for t in tgt_list:
250         t.in_library = []
251
252     for t in tgt_list:
253         if t.samba_type in [ 'LIBRARY' ]:
254             for obj in t.samba_deps_extended:
255                 t2 = bld.name_to_obj(obj, bld.env)
256                 if t2 and t2.samba_type in [ 'SUBSYSTEM', 'ASN1' ]:
257                     if not t.sname in t2.in_library:
258                         t2.in_library.append(t.sname)
259
260
261 def check_library_deps(bld, t):
262     '''check that all the autodeps that have mutual dependency of this
263     target are in the same library as the target'''
264
265     name = real_name(t.sname)
266
267     if len(t.in_library) > 1:
268         Logs.warn("WARNING: Target '%s' in multiple libraries: %s" % (t.sname, t.in_library))
269
270     for dep in t.autodeps:
271         t2 = bld.name_to_obj(dep, bld.env)
272         if t2 is None:
273             continue
274         for dep2 in t2.autodeps:
275             if dep2 == name and t.in_library != t2.in_library:
276                 Logs.warn("WARNING: mutual dependency %s <=> %s" % (name, real_name(t2.sname)))
277                 Logs.warn("Libraries should match. %s != %s" % (t.in_library, t2.in_library))
278                 # raise Utils.WafError("illegal mutual dependency")
279
280
281 def check_syslib_collisions(bld, tgt_list):
282     '''check if a target has any symbol collisions with a syslib
283
284     We do not want any code in Samba to use a symbol name from a
285     system library. The chance of that causing problems is just too
286     high. Note that libreplace uses a rep_XX approach of renaming
287     symbols via macros
288     '''
289
290     has_error = False
291     for t in tgt_list:
292         for lib in bld.env.syslib_symbols:
293             common = t.public_symbols.intersection(bld.env.syslib_symbols[lib])
294             if common:
295                 Logs.error("ERROR: Target '%s' has symbols '%s' which is also in syslib '%s'" % (t.sname, common, lib))
296                 has_error = True
297     if has_error:
298         raise Utils.WafError("symbols in common with system libraries")
299
300
301 def check_dependencies(bld, t):
302     '''check for depenencies that should be changed'''
303
304     if bld.name_to_obj(t.sname + ".objlist", bld.env):
305         return
306
307     targets = LOCAL_CACHE(bld, 'TARGET_TYPE')
308
309     remaining = t.undefined_symbols.copy()
310     remaining = remaining.difference(t.public_symbols)
311
312     sname = real_name(t.sname)
313
314     deps = set(t.samba_deps)
315     for d in t.samba_deps:
316         if targets[d] in [ 'EMPTY', 'DISABLED', 'SYSLIB' ]:
317             continue
318         bld.ASSERT(d in bld.env.public_symbols, "Failed to find symbol list for dependency '%s'" % d)
319         diff = remaining.intersection(bld.env.public_symbols[d])
320         if not diff and targets[sname] != 'LIBRARY':
321             Logs.info("Target '%s' has no dependency on %s" % (sname, d))
322         else:
323             remaining = remaining.difference(diff)
324
325     t.unsatisfied_symbols = set()
326     needed = {}
327     for sym in remaining:
328         if sym in bld.env.symbol_map:
329             dep = bld.env.symbol_map[sym]
330             if not dep[0] in needed:
331                 needed[dep[0]] = set()
332             needed[dep[0]].add(sym)
333         else:
334             t.unsatisfied_symbols.add(sym)
335
336     for dep in needed:
337         Logs.info("Target '%s' should add dep '%s' for symbols %s" % (sname, dep, " ".join(needed[dep])))
338
339
340
341 def check_syslib_dependencies(bld, t):
342     '''check for syslib depenencies'''
343
344     if bld.name_to_obj(t.sname + ".objlist", bld.env):
345         return
346
347     sname = real_name(t.sname)
348
349     remaining = set()
350
351     features = TO_LIST(t.features)
352     if 'pyembed' in features or 'pyext' in features:
353         t.unsatisfied_symbols = t.unsatisfied_symbols.difference(bld.env.public_symbols['python'])
354
355     needed = {}
356     for sym in t.unsatisfied_symbols:
357         if sym in bld.env.symbol_map:
358             dep = bld.env.symbol_map[sym][0]
359             if dep == 'c':
360                 continue
361             if not dep in needed:
362                 needed[dep] = set()
363             needed[dep].add(sym)
364         else:
365             remaining.add(sym)
366
367     for dep in needed:
368         Logs.info("Target '%s' should add syslib dep '%s' for symbols %s" % (sname, dep, " ".join(needed[dep])))
369
370     if remaining:
371         debug("deps: Target '%s' has unsatisfied symbols: %s" % (sname, " ".join(remaining)))
372
373
374
375 def symbols_symbolcheck(task):
376     '''check the internal dependency lists'''
377     bld = task.env.bld
378     tgt_list = get_tgt_list(bld)
379
380     build_symbol_sets(bld, tgt_list)
381     build_library_names(bld, tgt_list)
382
383     for t in tgt_list:
384         t.autodeps = set()
385         if getattr(t, 'source', ''):
386             build_autodeps(bld, t)
387
388     for t in tgt_list:
389         check_dependencies(bld, t)
390
391     for t in tgt_list:
392         check_library_deps(bld, t)
393
394 def symbols_syslibcheck(task):
395     '''check the syslib dependencies'''
396     bld = task.env.bld
397     tgt_list = get_tgt_list(bld)
398
399     build_syslib_sets(bld, tgt_list)
400     check_syslib_collisions(bld, tgt_list)
401
402     for t in tgt_list:
403         check_syslib_dependencies(bld, t)
404
405
406 def check_why_needed(bld, target, subsystem):
407     """check why 'target' needs to link to 'subsystem'"""
408     Logs.info("Checking why %s needs to link to %s" % (target, subsystem))
409     if not target in bld.env.used_symbols:
410         Logs.warn("unable to find target %s in used_symbols dict" % target)
411         return
412     if not subsystem in bld.env.public_symbols:
413         Logs.warn("unable to find subsystem %s in public_symbols dict" % subsystem)
414         return
415     overlap = bld.env.used_symbols[target].intersection(bld.env.public_symbols[subsystem])
416     if not overlap:
417         Logs.info("target %s doesn't use any public symbols from %s" % (target, subsystem))
418     else:
419         Logs.info("target %s uses %s from %s" % (target, overlap, subsystem))
420
421
422
423 def symbols_dupcheck(task):
424     '''check for symbols defined in two different subsystems'''
425     bld = task.env.bld
426     tgt_list = get_tgt_list(bld)
427
428     Logs.info("Checking for duplicate symbols")
429     for sym in bld.env.symbol_map:
430         subsystems = bld.env.symbol_map[sym]
431         if len(subsystems) == 1:
432             continue
433         Logs.info("symbol %s appears in %s" % (sym, subsystems))
434
435     # use this type of call to find why a library is needed
436     check_why_needed(bld, 'smbd/smbd', 'gensec')
437
438
439 def SYMBOL_CHECK(bld):
440     '''check our dependency lists'''
441     if Options.options.SYMBOLCHECK:
442         bld.SET_BUILD_GROUP('symbolcheck')
443         task = bld(rule=symbols_symbolcheck, always=True, name='symbol checking')
444         task.env.bld = bld
445
446         bld.SET_BUILD_GROUP('syslibcheck')
447         task = bld(rule=symbols_syslibcheck, always=True, name='syslib checking')
448         task.env.bld = bld
449
450         bld.SET_BUILD_GROUP('syslibcheck')
451         task = bld(rule=symbols_dupcheck, always=True, name='symbol duplicate checking')
452         task.env.bld = bld
453
454 Build.BuildContext.SYMBOL_CHECK = SYMBOL_CHECK