ctdb-tcp: Make error handling for outbound connection consistent
[Samba.git] / buildtools / wafsamba / samba_conftests.py
blobef632ba903369e4211991f17a3b204bcd96c3a2f
1 # a set of config tests that use the samba_autoconf functions
2 # to test for commonly needed configuration options
4 import os, shutil, re
5 from waflib import Build, Configure, Utils, Options, Logs, Errors
6 from waflib.Configure import conf
7 from samba_utils import TO_LIST, ADD_LD_LIBRARY_PATH, get_string
10 def add_option(self, *k, **kw):
11 '''syntax help: provide the "match" attribute to opt.add_option() so that folders can be added to specific config tests'''
12 Options.OptionsContext.parser = self
13 match = kw.get('match', [])
14 if match:
15 del kw['match']
16 opt = self.parser.add_option(*k, **kw)
17 opt.match = match
18 return opt
19 Options.OptionsContext.add_option = add_option
21 @conf
22 def check(self, *k, **kw):
23 '''Override the waf defaults to inject --with-directory options'''
25 if not 'env' in kw:
26 kw['env'] = self.env.derive()
28 # match the configuration test with specific options, for example:
29 # --with-libiconv -> Options.options.iconv_open -> "Checking for library iconv"
30 additional_dirs = []
31 if 'msg' in kw:
32 msg = kw['msg']
33 for x in Options.OptionsContext.parser.parser.option_list:
34 if getattr(x, 'match', None) and msg in x.match:
35 d = getattr(Options.options, x.dest, '')
36 if d:
37 additional_dirs.append(d)
39 # we add the additional dirs twice: once for the test data, and again if the compilation test suceeds below
40 def add_options_dir(dirs, env):
41 for x in dirs:
42 if not x in env.CPPPATH:
43 env.CPPPATH = [os.path.join(x, 'include')] + env.CPPPATH
44 if not x in env.LIBPATH:
45 env.LIBPATH = [os.path.join(x, 'lib')] + env.LIBPATH
47 add_options_dir(additional_dirs, kw['env'])
49 self.validate_c(kw)
50 self.start_msg(kw['msg'])
51 ret = None
52 try:
53 ret = self.run_c_code(*k, **kw)
54 except Configure.ConfigurationError as e:
55 self.end_msg(kw['errmsg'], 'YELLOW')
56 if 'mandatory' in kw and kw['mandatory']:
57 if Logs.verbose > 1:
58 raise
59 else:
60 self.fatal('the configuration failed (see %r)' % self.log.name)
61 else:
62 kw['success'] = ret
63 self.end_msg(self.ret_msg(kw['okmsg'], kw))
65 # success! keep the CPPPATH/LIBPATH
66 add_options_dir(additional_dirs, self.env)
68 self.post_check(*k, **kw)
69 if not kw.get('execute', False):
70 return ret == 0
71 return ret
74 @conf
75 def CHECK_ICONV(conf, define='HAVE_NATIVE_ICONV'):
76 '''check if the iconv library is installed
77 optionally pass a define'''
78 if conf.CHECK_FUNCS_IN('iconv_open', 'iconv', checklibc=True, headers='iconv.h'):
79 conf.DEFINE(define, 1)
80 return True
81 return False
84 @conf
85 def CHECK_LARGEFILE(conf, define='HAVE_LARGEFILE'):
86 '''see what we need for largefile support'''
87 getconf_cflags = conf.CHECK_COMMAND(['getconf', 'LFS_CFLAGS']);
88 if getconf_cflags is not False:
89 if (conf.CHECK_CODE('if (sizeof(off_t) < 8) return 1',
90 define='WORKING_GETCONF_LFS_CFLAGS',
91 execute=True,
92 cflags=getconf_cflags,
93 msg='Checking getconf large file support flags work')):
94 conf.ADD_CFLAGS(getconf_cflags)
95 getconf_cflags_list=TO_LIST(getconf_cflags)
96 for flag in getconf_cflags_list:
97 if flag[:2] == "-D":
98 flag_split = flag[2:].split('=')
99 if len(flag_split) == 1:
100 conf.DEFINE(flag_split[0], '1')
101 else:
102 conf.DEFINE(flag_split[0], flag_split[1])
104 if conf.CHECK_CODE('if (sizeof(off_t) < 8) return 1',
105 define,
106 execute=True,
107 msg='Checking for large file support without additional flags'):
108 return True
110 if conf.CHECK_CODE('if (sizeof(off_t) < 8) return 1',
111 define,
112 execute=True,
113 cflags='-D_FILE_OFFSET_BITS=64',
114 msg='Checking for -D_FILE_OFFSET_BITS=64'):
115 conf.DEFINE('_FILE_OFFSET_BITS', 64)
116 return True
118 if conf.CHECK_CODE('if (sizeof(off_t) < 8) return 1',
119 define,
120 execute=True,
121 cflags='-D_LARGE_FILES',
122 msg='Checking for -D_LARGE_FILES'):
123 conf.DEFINE('_LARGE_FILES', 1)
124 return True
125 return False
128 @conf
129 def CHECK_C_PROTOTYPE(conf, function, prototype, define, headers=None, msg=None):
130 '''verify that a C prototype matches the one on the current system'''
131 if not conf.CHECK_DECLS(function, headers=headers):
132 return False
133 if not msg:
134 msg = 'Checking C prototype for %s' % function
135 return conf.CHECK_CODE('%s; void *_x = (void *)%s' % (prototype, function),
136 define=define,
137 local_include=False,
138 headers=headers,
139 link=False,
140 execute=False,
141 msg=msg)
144 @conf
145 def CHECK_CHARSET_EXISTS(conf, charset, outcharset='UCS-2LE', headers=None, define=None):
146 '''check that a named charset is able to be used with iconv_open() for conversion
147 to a target charset
149 msg = 'Checking if can we convert from %s to %s' % (charset, outcharset)
150 if define is None:
151 define = 'HAVE_CHARSET_%s' % charset.upper().replace('-','_')
152 return conf.CHECK_CODE('''
153 iconv_t cd = iconv_open("%s", "%s");
154 if (cd == 0 || cd == (iconv_t)-1) return -1;
155 ''' % (charset, outcharset),
156 define=define,
157 execute=True,
158 msg=msg,
159 lib='iconv',
160 headers=headers)
162 def find_config_dir(conf):
163 '''find a directory to run tests in'''
164 k = 0
165 while k < 10000:
166 dir = os.path.join(conf.bldnode.abspath(), '.conf_check_%d' % k)
167 try:
168 shutil.rmtree(dir)
169 except OSError:
170 pass
171 try:
172 os.stat(dir)
173 except:
174 break
175 k += 1
177 try:
178 os.makedirs(dir)
179 except:
180 conf.fatal('cannot create a configuration test folder %r' % dir)
182 try:
183 os.stat(dir)
184 except:
185 conf.fatal('cannot use the configuration test folder %r' % dir)
186 return dir
188 @conf
189 def CHECK_SHLIB_INTRASINC_NAME_FLAGS(conf, msg):
191 check if the waf default flags for setting the name of lib
192 are ok
195 snip = '''
196 int foo(int v) {
197 return v * 2;
200 return conf.check(features='c cshlib',vnum="1",fragment=snip,msg=msg, mandatory=False)
202 @conf
203 def CHECK_NEED_LC(conf, msg):
204 '''check if we need -lc'''
206 dir = find_config_dir(conf)
208 env = conf.env
210 bdir = os.path.join(dir, 'testbuild2')
211 if not os.path.exists(bdir):
212 os.makedirs(bdir)
215 subdir = os.path.join(dir, "liblctest")
217 os.makedirs(subdir)
219 Utils.writef(os.path.join(subdir, 'liblc1.c'), '#include <stdio.h>\nint lib_func(void) { FILE *f = fopen("foo", "r");}\n')
221 bld = Build.BuildContext()
222 bld.log = conf.log
223 bld.all_envs.update(conf.all_envs)
224 bld.all_envs['default'] = env
225 bld.lst_variants = bld.all_envs.keys()
226 bld.load_dirs(dir, bdir)
228 bld.rescan(bld.srcnode)
230 bld(features='c cshlib',
231 source='liblctest/liblc1.c',
232 ldflags=conf.env['EXTRA_LDFLAGS'],
233 target='liblc',
234 name='liblc')
236 try:
237 bld.compile()
238 conf.check_message(msg, '', True)
239 return True
240 except:
241 conf.check_message(msg, '', False)
242 return False
245 @conf
246 def CHECK_SHLIB_W_PYTHON(conf, msg):
247 '''check if we need -undefined dynamic_lookup'''
249 dir = find_config_dir(conf)
250 snip = '''
251 #include <Python.h>
252 #include <crt_externs.h>
253 #define environ (*_NSGetEnviron())
255 static PyObject *ldb_module = NULL;
256 int foo(int v) {
257 extern char **environ;
258 environ[0] = 1;
259 ldb_module = PyImport_ImportModule("ldb");
260 return v * 2;
263 return conf.check(features='c cshlib',uselib='PYEMBED',fragment=snip,msg=msg, mandatory=False)
265 # this one is quite complex, and should probably be broken up
266 # into several parts. I'd quite like to create a set of CHECK_COMPOUND()
267 # functions that make writing complex compound tests like this much easier
268 @conf
269 def CHECK_LIBRARY_SUPPORT(conf, rpath=False, version_script=False, msg=None):
270 '''see if the platform supports building libraries'''
272 if msg is None:
273 if rpath:
274 msg = "rpath library support"
275 else:
276 msg = "building library support"
278 dir = find_config_dir(conf)
280 bdir = os.path.join(dir, 'testbuild')
281 if not os.path.exists(bdir):
282 os.makedirs(bdir)
284 env = conf.env
286 subdir = os.path.join(dir, "libdir")
288 os.makedirs(subdir)
290 Utils.writef(os.path.join(subdir, 'lib1.c'), 'int lib_func(void) { return 42; }\n')
291 Utils.writef(os.path.join(dir, 'main.c'),
292 'int lib_func(void);\n'
293 'int main(void) {return !(lib_func() == 42);}\n')
295 bld = Build.BuildContext()
296 bld.log = conf.log
297 bld.all_envs.update(conf.all_envs)
298 bld.all_envs['default'] = env
299 bld.lst_variants = bld.all_envs.keys()
300 bld.load_dirs(dir, bdir)
302 bld.rescan(bld.srcnode)
304 ldflags = []
305 if version_script:
306 ldflags.append("-Wl,--version-script=%s/vscript" % bld.path.abspath())
307 Utils.writef(os.path.join(dir,'vscript'), 'TEST_1.0A2 { global: *; };\n')
309 bld(features='c cshlib',
310 source='libdir/lib1.c',
311 target='libdir/lib1',
312 ldflags=ldflags,
313 name='lib1')
315 o = bld(features='c cprogram',
316 source='main.c',
317 target='prog1',
318 uselib_local='lib1')
320 if rpath:
321 o.rpath=os.path.join(bdir, 'default/libdir')
323 # compile the program
324 try:
325 bld.compile()
326 except:
327 conf.check_message(msg, '', False)
328 return False
330 # path for execution
331 lastprog = o.link_task.outputs[0].abspath(env)
333 if not rpath:
334 if 'LD_LIBRARY_PATH' in os.environ:
335 old_ld_library_path = os.environ['LD_LIBRARY_PATH']
336 else:
337 old_ld_library_path = None
338 ADD_LD_LIBRARY_PATH(os.path.join(bdir, 'default/libdir'))
340 # we need to run the program, try to get its result
341 args = conf.SAMBA_CROSS_ARGS(msg=msg)
342 proc = Utils.subprocess.Popen([lastprog] + args,
343 stdout=Utils.subprocess.PIPE, stderr=Utils.subprocess.PIPE)
344 (out, err) = proc.communicate()
345 w = conf.log.write
346 w(str(out))
347 w('\n')
348 w(str(err))
349 w('\nreturncode %r\n' % proc.returncode)
350 ret = (proc.returncode == 0)
352 if not rpath:
353 os.environ['LD_LIBRARY_PATH'] = old_ld_library_path or ''
355 conf.check_message(msg, '', ret)
356 return ret
360 @conf
361 def CHECK_PERL_MANPAGE(conf, msg=None, section=None):
362 '''work out what extension perl uses for manpages'''
364 if msg is None:
365 if section:
366 msg = "perl man%s extension" % section
367 else:
368 msg = "perl manpage generation"
370 conf.start_msg(msg)
372 dir = find_config_dir(conf)
374 bdir = os.path.join(dir, 'testbuild')
375 if not os.path.exists(bdir):
376 os.makedirs(bdir)
378 Utils.writef(os.path.join(bdir, 'Makefile.PL'), """
379 use ExtUtils::MakeMaker;
380 WriteMakefile(
381 'NAME' => 'WafTest',
382 'EXE_FILES' => [ 'WafTest' ]
384 """)
385 back = os.path.abspath('.')
386 os.chdir(bdir)
387 proc = Utils.subprocess.Popen(['perl', 'Makefile.PL'],
388 stdout=Utils.subprocess.PIPE,
389 stderr=Utils.subprocess.PIPE)
390 (out, err) = proc.communicate()
391 os.chdir(back)
393 ret = (proc.returncode == 0)
394 if not ret:
395 conf.end_msg('not found', color='YELLOW')
396 return
398 if section:
399 man = Utils.readf(os.path.join(bdir,'Makefile'))
400 m = re.search('MAN%sEXT\s+=\s+(\w+)' % section, man)
401 if not m:
402 conf.end_msg('not found', color='YELLOW')
403 return
404 ext = m.group(1)
405 conf.end_msg(ext)
406 return ext
408 conf.end_msg('ok')
409 return True
412 @conf
413 def CHECK_COMMAND(conf, cmd, msg=None, define=None, on_target=True, boolean=False):
414 '''run a command and return result'''
415 if msg is None:
416 msg = 'Checking %s' % ' '.join(cmd)
417 conf.COMPOUND_START(msg)
418 cmd = cmd[:]
419 if on_target:
420 cmd.extend(conf.SAMBA_CROSS_ARGS(msg=msg))
421 try:
422 ret = get_string(Utils.cmd_output(cmd))
423 except:
424 conf.COMPOUND_END(False)
425 return False
426 if boolean:
427 conf.COMPOUND_END('ok')
428 if define:
429 conf.DEFINE(define, '1')
430 else:
431 ret = ret.strip()
432 conf.COMPOUND_END(ret)
433 if define:
434 conf.DEFINE(define, ret, quote=True)
435 return ret
438 @conf
439 def CHECK_UNAME(conf):
440 '''setup SYSTEM_UNAME_* defines'''
441 ret = True
442 for v in "sysname machine release version".split():
443 if not conf.CHECK_CODE('''
444 int printf(const char *format, ...);
445 struct utsname n;
446 if (uname(&n) == -1) return -1;
447 printf("%%s", n.%s);
448 ''' % v,
449 define='SYSTEM_UNAME_%s' % v.upper(),
450 execute=True,
451 define_ret=True,
452 quote=True,
453 headers='sys/utsname.h',
454 local_include=False,
455 msg="Checking uname %s type" % v):
456 ret = False
457 return ret
459 @conf
460 def CHECK_INLINE(conf):
461 '''check for the right value for inline'''
462 conf.COMPOUND_START('Checking for inline')
463 for i in ['inline', '__inline__', '__inline']:
464 ret = conf.CHECK_CODE('''
465 typedef int foo_t;
466 static %s foo_t static_foo () {return 0; }
467 %s foo_t foo () {return 0; }\n''' % (i, i),
468 define='INLINE_MACRO',
469 addmain=False,
470 link=False)
471 if ret:
472 if i != 'inline':
473 conf.DEFINE('inline', i, quote=False)
474 break
475 if not ret:
476 conf.COMPOUND_END(ret)
477 else:
478 conf.COMPOUND_END(i)
479 return ret
481 @conf
482 def CHECK_XSLTPROC_MANPAGES(conf):
483 '''check if xsltproc can run with the given stylesheets'''
486 if not conf.CONFIG_SET('XSLTPROC'):
487 conf.find_program('xsltproc', var='XSLTPROC')
488 if not conf.CONFIG_SET('XSLTPROC'):
489 return False
491 s='http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl'
492 conf.CHECK_COMMAND('%s --nonet %s 2> /dev/null' % (conf.env.get_flat('XSLTPROC'), s),
493 msg='Checking for stylesheet %s' % s,
494 define='XSLTPROC_MANPAGES', on_target=False,
495 boolean=True)
496 if not conf.CONFIG_SET('XSLTPROC_MANPAGES'):
497 print("A local copy of the docbook.xsl wasn't found on your system" \
498 " consider installing package like docbook-xsl")
501 # Determine the standard libpath for the used compiler,
502 # so we can later use that to filter out these standard
503 # library paths when some tools like cups-config or
504 # python-config report standard lib paths with their
505 # ldflags (-L...)
507 @conf
508 def CHECK_STANDARD_LIBPATH(conf):
509 # at least gcc and clang support this:
510 try:
511 cmd = conf.env.CC + ['-print-search-dirs']
512 out = get_string(Utils.cmd_output(cmd)).split('\n')
513 except ValueError:
514 # option not supported by compiler - use a standard list of directories
515 dirlist = [ '/usr/lib', '/usr/lib64' ]
516 except:
517 raise Errors.WafError('Unexpected error running "%s"' % (cmd))
518 else:
519 dirlist = []
520 for line in out:
521 line = line.strip()
522 if line.startswith("libraries: ="):
523 dirliststr = line[len("libraries: ="):]
524 dirlist = [ os.path.normpath(x) for x in dirliststr.split(':') ]
525 break
527 conf.env.STANDARD_LIBPATH = dirlist