build:wafsamba: Close file handles in the build scripts too
[sfrench/samba-autobuild/.git] / buildtools / wafsamba / samba_conftests.py
1 # a set of config tests that use the samba_autoconf functions
2 # to test for commonly needed configuration options
3
4 import os, shutil, re
5 import Build, Configure, Utils
6 from Configure import conf
7 import config_c
8 from samba_utils import *
9
10
11 def add_option(self, *k, **kw):
12     '''syntax help: provide the "match" attribute to opt.add_option() so that folders can be added to specific config tests'''
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.Handler.add_option = add_option
20
21 @conf
22 def check(self, *k, **kw):
23     '''Override the waf defaults to inject --with-directory options'''
24
25     if not 'env' in kw:
26         kw['env'] = self.env.copy()
27
28     # match the configuration test with speficic 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.Handler.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)
38
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
46
47     add_options_dir(additional_dirs, kw['env'])
48
49     self.validate_c(kw)
50     self.check_message_1(kw['msg'])
51     ret = None
52     try:
53         ret = self.run_c_code(*k, **kw)
54     except Configure.ConfigurationError, e:
55         self.check_message_2(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.check_message_2(self.ret_msg(kw['okmsg'], kw))
64
65         # success! keep the CPPPATH/LIBPATH
66         add_options_dir(additional_dirs, self.env)
67
68     self.post_check(*k, **kw)
69     if not kw.get('execute', False):
70         return ret == 0
71     return ret
72
73
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
82
83
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('return !(sizeof(off_t) >= 8)',
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])
103
104     if conf.CHECK_CODE('return !(sizeof(off_t) >= 8)',
105                        define,
106                        execute=True,
107                        msg='Checking for large file support without additional flags'):
108         return True
109
110     if conf.CHECK_CODE('return !(sizeof(off_t) >= 8)',
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
117
118     if conf.CHECK_CODE('return !(sizeof(off_t) >= 8)',
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
126
127
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)
142
143
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
148     '''
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)
161
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.blddir, '.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
176
177     try:
178         os.makedirs(dir)
179     except:
180         conf.fatal('cannot create a configuration test folder %r' % dir)
181
182     try:
183         os.stat(dir)
184     except:
185         conf.fatal('cannot use the configuration test folder %r' % dir)
186     return dir
187
188 @conf
189 def CHECK_SHLIB_INTRASINC_NAME_FLAGS(conf, msg):
190     '''
191         check if the waf default flags for setting the name of lib
192         are ok
193     '''
194
195     snip = '''
196 int foo(int v) {
197     return v * 2;
198 }
199 '''
200     return conf.check(features='cc cshlib',vnum="1",fragment=snip,msg=msg)
201
202 @conf
203 def CHECK_NEED_LC(conf, msg):
204     '''check if we need -lc'''
205
206     dir = find_config_dir(conf)
207
208     env = conf.env
209
210     bdir = os.path.join(dir, 'testbuild2')
211     if not os.path.exists(bdir):
212         os.makedirs(bdir)
213
214
215     subdir = os.path.join(dir, "liblctest")
216
217     os.makedirs(subdir)
218
219     Utils.writef(os.path.join(subdir, 'liblc1.c'), '#include <stdio.h>\nint lib_func(void) { FILE *f = fopen("foo", "r");}\n')
220
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)
227
228     bld.rescan(bld.srcnode)
229
230     bld(features='cc cshlib',
231         source='liblctest/liblc1.c',
232         ldflags=conf.env['EXTRA_LDFLAGS'],
233         target='liblc',
234         name='liblc')
235
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
243
244
245 @conf
246 def CHECK_SHLIB_W_PYTHON(conf, msg):
247     '''check if we need -undefined dynamic_lookup'''
248
249     dir = find_config_dir(conf)
250
251     env = conf.env
252
253     snip = '''
254 #include <Python.h>
255 #include <crt_externs.h>
256 #define environ (*_NSGetEnviron())
257
258 static PyObject *ldb_module = NULL;
259 int foo(int v) {
260     extern char **environ;
261     environ[0] = 1;
262     ldb_module = PyImport_ImportModule("ldb");
263     return v * 2;
264 }'''
265     return conf.check(features='cc cshlib',uselib='PYEMBED',fragment=snip,msg=msg)
266
267 # this one is quite complex, and should probably be broken up
268 # into several parts. I'd quite like to create a set of CHECK_COMPOUND()
269 # functions that make writing complex compound tests like this much easier
270 @conf
271 def CHECK_LIBRARY_SUPPORT(conf, rpath=False, version_script=False, msg=None):
272     '''see if the platform supports building libraries'''
273
274     if msg is None:
275         if rpath:
276             msg = "rpath library support"
277         else:
278             msg = "building library support"
279
280     dir = find_config_dir(conf)
281
282     bdir = os.path.join(dir, 'testbuild')
283     if not os.path.exists(bdir):
284         os.makedirs(bdir)
285
286     env = conf.env
287
288     subdir = os.path.join(dir, "libdir")
289
290     os.makedirs(subdir)
291
292     Utils.writef(os.path.join(subdir, 'lib1.c'), 'int lib_func(void) { return 42; }\n')
293     Utils.writef(os.path.join(dir, 'main.c'), 'int main(void) {return !(lib_func() == 42);}\n')
294
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)
301
302     bld.rescan(bld.srcnode)
303
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')
308
309     bld(features='cc cshlib',
310         source='libdir/lib1.c',
311         target='libdir/lib1',
312         ldflags=ldflags,
313         name='lib1')
314
315     o = bld(features='cc cprogram',
316             source='main.c',
317             target='prog1',
318             uselib_local='lib1')
319
320     if rpath:
321         o.rpath=os.path.join(bdir, 'default/libdir')
322
323     # compile the program
324     try:
325         bld.compile()
326     except:
327         conf.check_message(msg, '', False)
328         return False
329
330     # path for execution
331     lastprog = o.link_task.outputs[0].abspath(env)
332
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'))
339
340     # we need to run the program, try to get its result
341     args = conf.SAMBA_CROSS_ARGS(msg=msg)
342     proc = Utils.pproc.Popen([lastprog] + args, stdout=Utils.pproc.PIPE, stderr=Utils.pproc.PIPE)
343     (out, err) = proc.communicate()
344     w = conf.log.write
345     w(str(out))
346     w('\n')
347     w(str(err))
348     w('\nreturncode %r\n' % proc.returncode)
349     ret = (proc.returncode == 0)
350
351     if not rpath:
352         os.environ['LD_LIBRARY_PATH'] = old_ld_library_path or ''
353
354     conf.check_message(msg, '', ret)
355     return ret
356
357
358
359 @conf
360 def CHECK_PERL_MANPAGE(conf, msg=None, section=None):
361     '''work out what extension perl uses for manpages'''
362
363     if msg is None:
364         if section:
365             msg = "perl man%s extension" % section
366         else:
367             msg = "perl manpage generation"
368
369     conf.check_message_1(msg)
370
371     dir = find_config_dir(conf)
372
373     bdir = os.path.join(dir, 'testbuild')
374     if not os.path.exists(bdir):
375         os.makedirs(bdir)
376
377     Utils.writef(os.path.join(bdir, 'Makefile.PL'), """
378 use ExtUtils::MakeMaker;
379 WriteMakefile(
380     'NAME'    => 'WafTest',
381     'EXE_FILES' => [ 'WafTest' ]
382 );
383 """)
384     back = os.path.abspath('.')
385     os.chdir(bdir)
386     proc = Utils.pproc.Popen(['perl', 'Makefile.PL'],
387                              stdout=Utils.pproc.PIPE,
388                              stderr=Utils.pproc.PIPE)
389     (out, err) = proc.communicate()
390     os.chdir(back)
391
392     ret = (proc.returncode == 0)
393     if not ret:
394         conf.check_message_2('not found', color='YELLOW')
395         return
396
397     if section:
398         man = Utils.readf(os.path.join(bdir,'Makefile'))
399         m = re.search('MAN%sEXT\s+=\s+(\w+)' % section, man)
400         if not m:
401             conf.check_message_2('not found', color='YELLOW')
402             return
403         ext = m.group(1)
404         conf.check_message_2(ext)
405         return ext
406
407     conf.check_message_2('ok')
408     return True
409
410
411 @conf
412 def CHECK_COMMAND(conf, cmd, msg=None, define=None, on_target=True, boolean=False):
413     '''run a command and return result'''
414     if msg is None:
415         msg = 'Checking %s' % ' '.join(cmd)
416     conf.COMPOUND_START(msg)
417     cmd = cmd[:]
418     if on_target:
419         cmd.extend(conf.SAMBA_CROSS_ARGS(msg=msg))
420     try:
421         ret = Utils.cmd_output(cmd)
422     except:
423         conf.COMPOUND_END(False)
424         return False
425     if boolean:
426         conf.COMPOUND_END('ok')
427         if define:
428             conf.DEFINE(define, '1')
429     else:
430         ret = ret.strip()
431         conf.COMPOUND_END(ret)
432         if define:
433             conf.DEFINE(define, ret, quote=True)
434     return ret
435
436
437 @conf
438 def CHECK_UNAME(conf):
439     '''setup SYSTEM_UNAME_* defines'''
440     ret = True
441     for v in "sysname machine release version".split():
442         if not conf.CHECK_CODE('''
443                                struct utsname n;
444                                if (uname(&n) == -1) return -1;
445                                printf("%%s", n.%s);
446                                ''' % v,
447                                define='SYSTEM_UNAME_%s' % v.upper(),
448                                execute=True,
449                                define_ret=True,
450                                quote=True,
451                                headers='sys/utsname.h',
452                                local_include=False,
453                                msg="Checking uname %s type" % v):
454             ret = False
455     return ret
456
457 @conf
458 def CHECK_INLINE(conf):
459     '''check for the right value for inline'''
460     conf.COMPOUND_START('Checking for inline')
461     for i in ['inline', '__inline__', '__inline']:
462         ret = conf.CHECK_CODE('''
463         typedef int foo_t;
464         static %s foo_t static_foo () {return 0; }
465         %s foo_t foo () {return 0; }''' % (i, i),
466                               define='INLINE_MACRO',
467                               addmain=False,
468                               link=False)
469         if ret:
470             if i != 'inline':
471                 conf.DEFINE('inline', i, quote=False)
472             break
473     if not ret:
474         conf.COMPOUND_END(ret)
475     else:
476         conf.COMPOUND_END(i)
477     return ret
478
479 @conf
480 def CHECK_XSLTPROC_MANPAGES(conf):
481     '''check if xsltproc can run with the given stylesheets'''
482
483
484     if not conf.CONFIG_SET('XSLTPROC'):
485         conf.find_program('xsltproc', var='XSLTPROC')
486     if not conf.CONFIG_SET('XSLTPROC'):
487         return False
488
489     s='http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl'
490     conf.CHECK_COMMAND('%s --nonet %s 2> /dev/null' % (conf.env.XSLTPROC, s),
491                              msg='Checking for stylesheet %s' % s,
492                              define='XSLTPROC_MANPAGES', on_target=False,
493                              boolean=True)
494     if not conf.CONFIG_SET('XSLTPROC_MANPAGES'):
495         print "A local copy of the docbook.xsl wasn't found on your system" \
496               " consider installing package like docbook-xsl"
497
498 #
499 # Determine the standard libpath for the used compiler,
500 # so we can later use that to filter out these standard
501 # library paths when some tools like cups-config or
502 # python-config report standard lib paths with their
503 # ldflags (-L...)
504 #
505 @conf
506 def CHECK_STANDARD_LIBPATH(conf):
507     # at least gcc and clang support this:
508     try:
509         cmd = conf.env.CC + ['-print-search-dirs']
510         out = Utils.cmd_output(cmd).split('\n')
511     except ValueError:
512         # option not supported by compiler - use a standard list of directories
513         dirlist = [ '/usr/lib', '/usr/lib64' ]
514     except:
515         raise Utils.WafError('Unexpected error running "%s"' % (cmd))
516     else:
517         dirlist = []
518         for line in out:
519             line = line.strip()
520             if line.startswith("libraries: ="):
521                 dirliststr = line[len("libraries: ="):]
522                 dirlist = [ os.path.normpath(x) for x in dirliststr.split(':') ]
523                 break
524
525     conf.env.STANDARD_LIBPATH = dirlist
526
527
528 waf_config_c_parse_flags = config_c.parse_flags;
529 def samba_config_c_parse_flags(line1, uselib, env):
530     #
531     # We do a special treatment of the rpath components
532     # in the linkflags line, because currently the upstream
533     # parse_flags function is incomplete with respect to
534     # treatment of the rpath. The remainder of the linkflags
535     # line is later passed to the original funcion.
536     #
537     lst1 = shlex.split(line1)
538     lst2 = []
539     while lst1:
540         x = lst1.pop(0)
541
542         #
543         # NOTE on special treatment of -Wl,-R and -Wl,-rpath:
544         #
545         # It is important to not put a library provided RPATH
546         # into the LINKFLAGS but in the RPATH instead, since
547         # the provided LINKFLAGS get prepended to our own internal
548         # RPATH later, and hence can potentially lead to linking
549         # in too old versions of our internal libs.
550         #
551         # We do this filtering here on our own because of some
552         # bugs in the real parse_flags() function.
553         #
554         if x == '-Wl,-rpath' or x == '-Wl,-R':
555             x = lst1.pop(0)
556             if x.startswith('-Wl,'):
557                 rpath = x[4:]
558             else:
559                 rpath = x
560         elif x.startswith('-Wl,-R,'):
561             rpath = x[7:]
562         elif x.startswith('-Wl,-R'):
563             rpath = x[6:]
564         elif x.startswith('-Wl,-rpath,'):
565             rpath = x[11:]
566         else:
567             lst2.append(x)
568             continue
569
570         env.append_value('RPATH_' + uselib, rpath)
571
572     line2 = ' '.join(lst2)
573     waf_config_c_parse_flags(line2, uselib, env)
574
575     return
576 config_c.parse_flags = samba_config_c_parse_flags