Debian Codegraph @

buildlib/check-build

raw
1 #!/usr/bin/env python3
2 # Copyright 2017 Obsidian Research Corp.
3 # Licensed under BSD (MIT variant) or GPLv2. See COPYING.
4 """check-build - Run static checks on a build"""
5 from __future__ import print_function
6 import argparse
7 import inspect
8 import os
9 import re
10 import shutil
11 import subprocess
12 import tempfile
13 import sys
14 import copy
15 import shlex
16 import pipes
17 from contextlib import contextmanager;
18 from pkg_resources import parse_version
19
20 def get_src_dir():
21 """Get the source directory using git"""
22 git_top = subprocess.check_output(["git","rev-parse","--git-dir"]).decode().strip();
23 if git_top == ".git":
24 return ".";
25 return os.path.dirname(git_top);
26
27 def get_package_version(args):
28 """Return PACKAGE_VERSION from CMake"""
29 with open(os.path.join(args.SRC,"CMakeLists.txt")) as F:
30 for ln in F:
31 g = re.match(r'^set\(PACKAGE_VERSION "(.+)"\)',ln)
32 if g is None:
33 continue;
34 return g.group(1);
35 raise RuntimeError("Could not find version");
36
37 @contextmanager
38 def inDirectory(dir):
39 cdir = os.getcwd();
40 try:
41 os.chdir(dir);
42 yield True;
43 finally:
44 os.chdir(cdir);
45
46 @contextmanager
47 def private_tmp():
48 """Simple version of Python 3's tempfile.TemporaryDirectory"""
49 dfn = tempfile.mkdtemp();
50 try:
51 yield dfn;
52 finally:
53 shutil.rmtree(dfn);
54
55 # -------------------------------------------------------------------------
56
57 def get_symbol_vers(fn,exported=True):
58 """Return the symbol version suffixes from the ELF file, eg IB_VERBS_1.0, etc"""
59 syms = subprocess.check_output(["readelf","--wide","-s",fn]).decode();
60
61 go = False;
62 res = set();
63 for I in syms.splitlines():
64 if I.startswith("Symbol table '.dynsym'"):
65 go = True;
66 continue;
67
68 if I.startswith(" ") and go:
69 itms = I.split();
70 if exported:
71 if (len(itms) == 8 and itms[3] == "OBJECT" and
72 itms[4] == "GLOBAL" and itms[6] == "ABS"):
73 res.add(itms[7]);
74 else:
75 if (len(itms) >= 8 and itms[3] == "FUNC" and
76 itms[4] == "GLOBAL" and itms[6] == "UND"):
77 res.add(itms[7]);
78 else:
79 go = False;
80 if not res:
81 raise ValueError("Failed to read ELF symbol versions from %r"%(fn));
82 return res;
83
84 def symver_parse_version(ver):
85 return parse_version(ver.partition("_")[-1])
86
87 def check_lib_symver(args,fn):
88 g = re.match(r"lib([^.]+)\.so\.(\d+)\.(\d+)\.(.*)",fn);
89 if g.group(4) != args.PACKAGE_VERSION:
90 raise ValueError("Shared Library filename %r does not have the package version %r (%r)"%(
91 fn,args.PACKAGE_VERSION,g.groups()));
92
93 # umad/etc used the wrong symbol version name when they moved to soname 3.0
94 if g.group(1) == "ibumad":
95 newest_symver = "%s_%s.%s"%(g.group(1).upper(),'1',g.group(3));
96 elif g.group(1) == "ibmad":
97 newest_symver = "%s_%s.%s"%(g.group(1).upper(),'1',g.group(3));
98 elif g.group(1) == "ibnetdisc":
99 newest_symver = "%s_%s.%s"%(g.group(1).upper(),'1',g.group(3));
100 else:
101 newest_symver = "%s_%s.%s"%(g.group(1).upper(),g.group(2),g.group(3));
102
103 syms = get_symbol_vers(fn);
104 if newest_symver not in syms:
105 raise ValueError("Symbol version %r implied by filename %r not in ELF (%r)"%(
106 newest_symver,fn,syms));
107
108 # The private symbol tag should also be older than the package version
109 private = set(I for I in syms if "PRIVATE" in I)
110 if len(private) > 1:
111 raise ValueError("Too many private symbol versions in ELF %r (%r)"%(fn,private));
112 if private:
113 private_rel = list(private)[0].split('_')[-1];
114 if private_rel > args.PACKAGE_VERSION:
115 raise ValueError("Private Symbol Version %r is newer than the package version %r"%(
116 private,args.PACKAGE_VERSION));
117
118 syms = list(syms - private);
119 syms.sort(key=symver_parse_version)
120 if newest_symver != syms[-1]:
121 raise ValueError("Symbol version %r implied by filename %r not the newest in ELF (%r)"%(
122 newest_symver,fn,syms));
123
124 def test_lib_names(args):
125 """Check that the library filename matches the symbol versions"""
126 libd = os.path.join(args.BUILD,"lib");
127
128 # List of shlibs that follow the ABI guidelines
129 libs = {};
130 with inDirectory(libd):
131 for fn in os.listdir("."):
132 if os.path.islink(fn):
133 lfn = os.readlink(fn);
134 if not os.path.islink(lfn):
135 check_lib_symver(args,lfn);
136 # -------------------------------------------------------------------------
137
138 def check_verbs_abi(args,fn):
139 g = re.match(r"lib([^-]+)-rdmav(\d+).so",fn);
140 if g is None:
141 raise ValueError("Provider library has unknown file name format %r"%(fn));
142
143 private_ver = int(g.group(2));
144 syms = get_symbol_vers(fn,exported=False);
145 syms = {I.partition("@")[2] for I in syms};
146 assert "IBVERBS_PRIVATE_%u"%(private_ver) in syms;
147 assert len([I for I in syms if I.startswith("IBVERBS_PRIVATE")]) == 1;
148
149 def test_verbs_private(args):
150 """Check that the IBVERBS_PRIVATE symbols match the library name, eg that the
151 map file and the cmake stuff are in sync."""
152 libd = os.path.join(args.BUILD,"lib");
153 with inDirectory(libd):
154 for fn in os.listdir("."):
155 if not os.path.islink(fn) and "rdmav" in fn and fn.endswith(".so"):
156 check_verbs_abi(args,fn);
157
158 # -------------------------------------------------------------------------
159
160 def check_abi(args,fn):
161 g1 = re.match(r"lib([^.]+).so\.(.+)\.(.+)",fn);
162 g2 = re.match(r"lib([^.]+).so\.(.+\..+)",fn);
163 if g1 is None or g2 is None:
164 raise ValueError("Library has unknown file name format %r"%(fn));
165
166 ref_fn = os.path.join(args.SRC,"ABI",g1.group(1) + ".dump");
167 cur_fn = os.path.join(args.SRC,"ABI","current-" + g1.group(1) + ".dump");
168 subprocess.check_call(["abi-dumper",
169 "-lver",g2.group(1),
170 fn,
171 "-o",cur_fn]);
172
173 if not os.path.exists(ref_fn):
174 print("ABI file does not exist for %r"%(ref_fn), file=sys.stderr);
175 return False;
176
177 subprocess.check_call(["abi-compliance-checker",
178 "-l",g1.group(1),
179 "-old",ref_fn,
180 "-new",cur_fn]);
181
182 return True;
183
184 def test_verbs_uapi(args):
185 """Compare the ABI output from 'abi-dumper' between what is present in git and
186 what was built in this tree. This allows us to detect changes in ABI on
187 the -stable branch."""
188
189 # User must provide the ABI dir in the source tree
190 if not os.path.isdir(os.path.join(args.SRC,"ABI")):
191 print("ABI check skipped, no ABI/ directory.");
192 return;
193
194 libd = os.path.join(args.BUILD,"lib");
195 success = True;
196 with inDirectory(libd):
197 for fn in os.listdir("."):
198 if not os.path.islink(fn) and re.match(r"lib.+\.so\..+\..+",fn):
199 success = success & check_abi(args,fn);
200
201 assert success == True;
202
203 # -------------------------------------------------------------------------
204
205 def is_obsolete(fn):
206 """True if the header is obsolete and should not be compiled anyhow."""
207 with open(fn) as F:
208 for ln in F.readlines():
209 if re.search(r"#warning.*This header is obsolete",ln):
210 return True;
211 return False;
212
213 def is_fixup(fn):
214 """True if this is a fixup header, fixup headers are exempted because they
215 required includes are not the same for kernel headers (eg netinet/in.h)"""
216 if os.path.islink(fn):
217 return "buildlib/fixup-include/" in os.readlink(fn);
218 return False;
219
220 def get_headers(incdir):
221 includes = set();
222 for root,dirs,files in os.walk(incdir):
223 for I in files:
224 if I.endswith(".h"):
225 includes.add(os.path.join(root,I));
226 return includes;
227
228 def compile_test_headers(tmpd,incdir,includes,with_cxx=False):
229 cppflags = subprocess.check_output(["pkg-config","libnl-3.0","--cflags-only-I"]).decode().strip();
230 cppflags = "-I %s %s"%(incdir,cppflags)
231 with open(os.path.join(tmpd,"build.ninja"),"wt") as F:
232 print("rule comp", file=F);
233 print(" command = %s -Werror -c %s $in -o $out"%(args.CC,cppflags), file=F);
234 print(" description=Header check for $in", file=F);
235 print("rule comp_cxx", file=F);
236 print(" command = %s -Werror -c %s $in -o $out"%(args.CXX,cppflags), file=F);
237 print(" description=Header C++ check for $in", file=F);
238 count = 0;
239 for I in sorted(includes):
240 if is_obsolete(I) or is_fixup(I):
241 continue;
242 print("build %s : comp %s"%("out%d.o"%(count),I), file=F);
243 print("default %s"%("out%d.o"%(count)), file=F);
244 print("build %s : comp_cxx %s"%("outxx%d.o"%(count),I), file=F);
245 if with_cxx:
246 print("default %s"%("outxx%d.o"%(count)), file=F);
247 count = count + 1;
248 subprocess.check_call(["ninja"],cwd=tmpd);
249
250 def test_published_headers(args):
251 """Test that every header file can be included on its own, and has no obvious
252 implicit dependencies. This is intended as a first pass check of the public
253 installed API headers"""
254 incdir = os.path.abspath(os.path.join(args.BUILD,"include"));
255 includes = get_headers(incdir);
256
257 # Make a little ninja file to compile each header
258 with private_tmp() as tmpd:
259 compile_test_headers(tmpd,incdir,includes);
260
261 # -------------------------------------------------------------------------
262
263 allowed_uapi_headers = {
264 # This header is installed in all supported distributions
265 "rdma/ib_user_sa.h",
266 "rdma/ib_user_verbs.h",
267 "linux/stddef.h",
268 }
269
270 non_cxx_headers = {
271 "infiniband/arch.h",
272 "infiniband/ib.h",
273 "infiniband/ib_user_ioctl_verbs.h",
274 "infiniband/ibnetdisc_osd.h",
275 "infiniband/mad_osd.h",
276 "infiniband/mlx5_api.h",
277 "infiniband/mlx5_user_ioctl_verbs.h",
278 "infiniband/opcode.h",
279 "infiniband/sa-kern-abi.h",
280 "infiniband/sa.h",
281 "infiniband/verbs_api.h",
282 "rdma/rdma_cma_abi.h",
283 }
284
285 def test_installed_headers(args):
286 """This test also checks that the public headers can be compiled on their own,
287 but goes further and confirms that the public headers do not depend on any
288 internal headers, or kernel kAPI headers."""
289 with private_tmp() as tmpd:
290 env = copy.deepcopy(os.environ);
291 env["DESTDIR"] = tmpd;
292 subprocess.check_output(["ninja","install"],env=env,cwd=args.BUILD);
293
294 includes = get_headers(tmpd);
295 incdir = os.path.commonprefix(list(includes));
296 rincludes = {I[len(incdir):] for I in includes};
297
298 bincdir = os.path.abspath(os.path.join(args.BUILD,"include"));
299 all_includes = set();
300 for I in get_headers(bincdir):
301 if not is_fixup(I) and not is_obsolete(I):
302 all_includes.add(I[len(bincdir)+1:]);
303
304 # Drop error includes for any include file that is internal, this way
305 # when we compile the public headers any include of an internal header
306 # will fail.
307 for I in sorted(all_includes - rincludes):
308 if I in allowed_uapi_headers:
309 continue;
310
311 I = os.path.join(incdir,I)
312 dfn = os.path.dirname(I);
313 if not os.path.isdir(dfn):
314 os.makedirs(dfn);
315 assert not os.path.exists(I);
316 with open(I,"w") as F:
317 print('#error "Private internal header"', file=F);
318
319 # Roughly check that the headers have the extern "C" for C++
320 # compilation.
321 for I in sorted(rincludes - non_cxx_headers):
322 with open(os.path.join(incdir,I)) as F:
323 if 'extern "C" {' not in F.read():
324 raise ValueError("No extern C in %r"%(I));
325
326 compile_test_headers(tmpd,incdir,includes,with_cxx=True);
327
328 # -------------------------------------------------------------------------
329
330
331 def get_symbol_names(fn):
332 """Return the defined, public, symbols from a ELF shlib"""
333 syms = subprocess.check_output(["readelf", "--wide", "-s", fn]).decode()
334 go = False
335 res = set()
336 for I in syms.splitlines():
337 if I.startswith("Symbol table '.dynsym'"):
338 go = True
339 continue
340
341 if I.startswith(" ") and go:
342 g = re.match(
343 r"\s+\d+:\s+[0-9a-f]+\s+\d+.*(?:FUNC|OBJECT)\s+GLOBAL\s+DEFAULT\s+\d+\s+(\S+)@@(\S+)$",
344 I)
345 if not g or "PRIVATE" in g.group(2):
346 continue
347 res.add(g.group(1))
348 else:
349 go = False
350
351 return res
352
353
354 def get_cc_args_from_pkgconfig(args, name, static):
355 """Get the compile arguments from pkg-config for the named librarary"""
356 os.environ["PKG_CONFIG_PATH"] = os.path.join(args.BUILD, "lib",
357 "pkgconfig")
358 flags = ["pkg-config", "--errors-to-stdout", "--cflags", "--libs"]
359 if static:
360 flags.append("--static")
361 opts = subprocess.check_output(flags + ["lib" + name]).decode()
362 opts = shlex.split(opts)
363
364 opts.insert(0, "-Wall")
365 opts.insert(0, "-Werror")
366 opts.insert(0, "-L%s" % (os.path.join(args.BUILD, "lib")))
367 opts.insert(1, "-I%s" % (os.path.join(args.BUILD, "include")))
368 if not static:
369 return opts
370
371 # Only static link the pkg-config stuff, otherwise we get warnings about
372 # static linking portions of glibc that need NSS.
373 opts.insert(0, "-Wl,-Bstatic")
374 opts.append("-Wl,-Bdynamic")
375
376 # We need this extra libpthread/m because libnl's pkgconfig file is
377 # broken and doesn't include the private libraries it requires. :(
378 if "-lnl-3" in opts:
379 opts.append("-lm")
380 opts.append("-lpthread")
381
382 # Put glibc associated libraries out side the static link section,
383 if "-lpthread" in opts:
384 while "-lpthread" in opts:
385 opts.remove("-lpthread")
386 opts.append("-lpthread")
387 if "-lm" in opts:
388 while "-lm" in opts:
389 opts.remove("-lm")
390 opts.append("-lm")
391 return opts
392
393
394 def compile_ninja(args, Fninja, name, cfn, opts):
395 print("""
396 rule comp_{name}
397 command = {CC} -Wall -o $out $in {opts}
398 description = Compile and link $out
399 build {name} : comp_{name} {cfn}
400 default {name}""".format(
401 name=name,
402 CC=args.CC,
403 cfn=cfn,
404 opts=" ".join(pipes.quote(I) for I in opts)), file=Fninja)
405
406
407 def get_providers(args):
408 """Return a list of provider names"""
409 return set(
410 I for I in os.listdir(os.path.join(args.SRC, "providers"))
411 if not I.startswith("."))
412
413
414 def check_static_lib(args, tmpd, Fninja, static_lib, shared_lib, name):
415 syms = get_symbol_names(shared_lib)
416 if not syms:
417 return
418
419 cfn = os.path.join(tmpd, "%s-test.c" % (name))
420 with open(cfn, "wt") as F:
421 F.write("#include <stdio.h>\n")
422 for I in syms:
423 F.write("extern void %s(void);\n" % (I))
424 F.write("int main(int argc,const char *argv[]) {\n")
425 for I in syms:
426 F.write('printf("%%p",&%s);\n' % (I))
427 F.write("return 0; }\n")
428
429 compile_ninja(args, Fninja, "%s-static-out" % (name), cfn,
430 get_cc_args_from_pkgconfig(args, name, static=True))
431 compile_ninja(args, Fninja, "%s-shared-out" % (name), cfn,
432 get_cc_args_from_pkgconfig(args, name, static=False))
433
434
435 def check_static_providers(args, tmpd, Fninja):
436 """Test that expected values for RDMA_STATIC_PROVIDERS are accepted and the
437 link works"""
438 cfn = os.path.join(tmpd, "provider-test.c")
439 with open(cfn, "wt") as F:
440 F.write("#include <infiniband/verbs.h>\n")
441 F.write("int main(int argc,const char *argv[]) {\n")
442 F.write('ibv_get_device_list(NULL);\n')
443 F.write("return 0; }\n")
444
445 opts = get_cc_args_from_pkgconfig(
446 args, "ibverbs", static=True)
447
448 providers = get_providers(args)
449 for I in sorted(providers | {
450 "none",
451 "all",
452 }):
453 compile_ninja(args, Fninja, "providers-%s-static-out" % (I), cfn,
454 ["-DRDMA_STATIC_PROVIDERS=%s" % (I)] + opts)
455
456 compile_ninja(
457 args, Fninja, "providers-static-out", cfn,
458 ["-DRDMA_STATIC_PROVIDERS=%s" % (",".join(providers))] + opts)
459
460
461 def test_static_libs(args):
462 """Compile then link statically and dynamically a dummy program that touches
463 every symbol in the libraries using pkgconfig output to guide the link
464 options. This tests that pkgconfig is setup properly and that all the
465 magic with incorporating the internal libraries for static linking has
466 done its job."""
467 libd = os.path.join(args.BUILD, "lib")
468 success = True
469 libs = []
470 with inDirectory(libd):
471 fns = set(fn for fn in os.listdir(".") if not os.path.islink(fn))
472 for static_lib in fns:
473 g = re.match(r"lib(.+)\.a$", static_lib)
474 if g:
475 for shared_lib in fns:
476 if re.match(r"lib%s.*\.so" % (g.group(1)), shared_lib):
477 libs.append((os.path.join(libd, static_lib),
478 os.path.join(libd, shared_lib),
479 g.group(1)))
480 break
481 else:
482 raise ValueError(
483 "Failed to find matching shared library for %r" %
484 (static_lib))
485
486 with private_tmp() as tmpd:
487 with open(os.path.join(tmpd, "build.ninja"), "wt") as Fninja:
488 for I in libs:
489 check_static_lib(args, tmpd, Fninja, I[0], I[1], I[2])
490 check_static_providers(args, tmpd, Fninja)
491 subprocess.check_call(["ninja"], cwd=tmpd)
492
493
494 # -------------------------------------------------------------------------
495
496 parser = argparse.ArgumentParser(description='Run build time tests')
497 parser.add_argument("--build",default=os.getcwd(),dest="BUILD",
498 help="Build directory to inpsect");
499 parser.add_argument("--src",default=None,dest="SRC",
500 help="Top of the source tree");
501 parser.add_argument("--cc",default="cc",dest="CC",
502 help="C compiler to use");
503 parser.add_argument("--cxx",default="c++",dest="CXX",
504 help="C++ compiler to use");
505 args = parser.parse_args();
506
507 if args.SRC is None:
508 args.SRC = get_src_dir();
509 args.SRC = os.path.abspath(args.SRC);
510 args.PACKAGE_VERSION = get_package_version(args);
511
512 funcs = globals();
513 for k,v in list(funcs.items()):
514 if k.startswith("test_") and inspect.isfunction(v):
515 v(args);