summaryrefslogtreecommitdiffstats
path: root/buildtools/wafsamba/samba_conftests.py
blob: 0274f665a68d8a8e38423908fe15ade1ff0c9b0e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# a set of config tests that use the samba_autoconf functions
# to test for commonly needed configuration options

import os, shutil, re
import Build, Configure, Utils
from Configure import conf
from samba_utils import *


def add_option(self, *k, **kw):
    '''syntax help: provide the "match" attribute to opt.add_option() so that folders can be added to specific config tests'''
    match = kw.get('match', [])
    if match:
        del kw['match']
    opt = self.parser.add_option(*k, **kw)
    opt.match = match
    return opt
Options.Handler.add_option = add_option

@conf
def check(self, *k, **kw):
    '''Override the waf defaults to inject --with-directory options'''

    if not 'env' in kw:
        kw['env'] = self.env.copy()

    # match the configuration test with speficic options, for example:
    # --with-libiconv -> Options.options.iconv_open -> "Checking for library iconv"
    additional_dirs = []
    if 'msg' in kw:
        msg = kw['msg']
        for x in Options.Handler.parser.parser.option_list:
             if getattr(x, 'match', None) and msg in x.match:
                 d = getattr(Options.options, x.dest, '')
                 if d:
                     additional_dirs.append(d)

    # we add the additional dirs twice: once for the test data, and again if the compilation test suceeds below
    def add_options_dir(dirs, env):
        for x in dirs:
             if not x in env.CPPPATH:
                 env.CPPPATH = [os.path.join(x, 'include')] + env.CPPPATH
             if not x in env.LIBPATH:
                 env.LIBPATH = [os.path.join(x, 'lib')] + env.LIBPATH

    add_options_dir(additional_dirs, kw['env'])

    self.validate_c(kw)
    self.check_message_1(kw['msg'])
    ret = None
    try:
        ret = self.run_c_code(*k, **kw)
    except Configure.ConfigurationError, e:
        self.check_message_2(kw['errmsg'], 'YELLOW')
        if 'mandatory' in kw and kw['mandatory']:
            if Logs.verbose > 1:
                raise
            else:
                self.fatal('the configuration failed (see %r)' % self.log.name)
    else:
        kw['success'] = ret
        self.check_message_2(self.ret_msg(kw['okmsg'], kw))

        # success! keep the CPPPATH/LIBPATH
        add_options_dir(additional_dirs, self.env)

    self.post_check(*k, **kw)
    if not kw.get('execute', False):
        return ret == 0
    return ret


@conf
def CHECK_ICONV(conf, define='HAVE_NATIVE_ICONV'):
    '''check if the iconv library is installed
       optionally pass a define'''
    if conf.CHECK_FUNCS_IN('iconv_open', 'iconv', checklibc=True, headers='iconv.h'):
        conf.DEFINE(define, 1)
        return True
    return False


@conf
def CHECK_LARGEFILE(conf, define='HAVE_LARGEFILE'):
    '''see what we need for largefile support'''
    getconf_cflags = conf.CHECK_COMMAND(['getconf', 'LFS_CFLAGS']);
    if getconf_cflags is not False:
        if (conf.CHECK_CODE('return !(sizeof(off_t) >= 8)',
                            define='WORKING_GETCONF_LFS_CFLAGS',
                            execute=True,
                            cflags=getconf_cflags,
                            msg='Checking getconf large file support flags work')):
            conf.ADD_CFLAGS(getconf_cflags)
            getconf_cflags_list=TO_LIST(getconf_cflags)
            for flag in getconf_cflags_list:
                if flag[:2] == "-D":
                    flag_split = flag[2:].split('=')
                    if len(flag_split) == 1:
                        conf.DEFINE(flag_split[0], '1')
                    else:
                        conf.DEFINE(flag_split[0], flag_split[1])

    if conf.CHECK_CODE('return !(sizeof(off_t) >= 8)',
                       define,
                       execute=True,
                       msg='Checking for large file support without additional flags'):
        return True

    if conf.CHECK_CODE('return !(sizeof(off_t) >= 8)',
                       define,
                       execute=True,
                       cflags='-D_FILE_OFFSET_BITS=64',
                       msg='Checking for -D_FILE_OFFSET_BITS=64'):
        conf.DEFINE('_FILE_OFFSET_BITS', 64)
        return True

    if conf.CHECK_CODE('return !(sizeof(off_t) >= 8)',
                       define,
                       execute=True,
                       cflags='-D_LARGE_FILES',
                       msg='Checking for -D_LARGE_FILES'):
        conf.DEFINE('_LARGE_FILES', 1)
        return True
    return False


@conf
def CHECK_C_PROTOTYPE(conf, function, prototype, define, headers=None, msg=None):
    '''verify that a C prototype matches the one on the current system'''
    if not conf.CHECK_DECLS(function, headers=headers):
        return False
    if not msg:
        msg = 'Checking C prototype for %s' % function
    return conf.CHECK_CODE('%s; void *_x = (void *)%s' % (prototype, function),
                           define=define,
                           local_include=False,
                           headers=headers,
                           link=False,
                           execute=False,
                           msg=msg)


@conf
def CHECK_CHARSET_EXISTS(conf, charset, outcharset='UCS-2LE', headers=None, define=None):
    '''check that a named charset is able to be used with iconv_open() for conversion
    to a target charset
    '''
    msg = 'Checking if can we convert from %s to %s' % (charset, outcharset)
    if define is None:
        define = 'HAVE_CHARSET_%s' % charset.upper().replace('-','_')
    return conf.CHECK_CODE('''
                           iconv_t cd = iconv_open("%s", "%s");
                           if (cd == 0 || cd == (iconv_t)-1) return -1;
                           ''' % (charset, outcharset),
                           define=define,
                           execute=True,
                           msg=msg,
                           lib='iconv',
                           headers=headers)

def find_config_dir(conf):
    '''find a directory to run tests in'''
    k = 0
    while k < 10000:
        dir = os.path.join(conf.blddir, '.conf_check_%d' % k)
        try:
            shutil.rmtree(dir)
        except OSError:
            pass
        try:
            os.stat(dir)
        except:
            break
        k += 1

    try:
        os.makedirs(dir)
    except:
        conf.fatal('cannot create a configuration test folder %r' % dir)

    try:
        os.stat(dir)
    except:
        conf.fatal('cannot use the configuration test folder %r' % dir)
    return dir

@conf
def CHECK_SHLIB_INTRASINC_NAME_FLAGS(conf, msg):
    '''
        check if the waf default flags for setting the name of lib
        are ok
    '''

    snip = '''
int foo(int v) {
    return v * 2;
}
'''
    return conf.check(features='cc cshlib',vnum="1",fragment=snip,msg=msg)

@conf
def CHECK_NEED_LC(conf, msg):
    '''check if we need -lc'''

    dir = find_config_dir(conf)

    env = conf.env

    bdir = os.path.join(dir, 'testbuild2')
    if not os.path.exists(bdir):
        os.makedirs(bdir)


    subdir = os.path.join(dir, "liblctest")

    os.makedirs(subdir)

    dest = open(os.path.join(subdir, 'liblc1.c'), 'w')
    dest.write('#include <stdio.h>\nint lib_func(void) { FILE *f = fopen("foo", "r");}\n')
    dest.close()

    bld = Build.BuildContext()
    bld.log = conf.log
    bld.all_envs.update(conf.all_envs)
    bld.all_envs['default'] = env
    bld.lst_variants = bld.all_envs.keys()
    bld.load_dirs(dir, bdir)

    bld.rescan(bld.srcnode)

    bld(features='cc cshlib',
        source='liblctest/liblc1.c',
        ldflags=conf.env['EXTRA_LDFLAGS'],
        target='liblc',
        name='liblc')

    try:
        bld.compile()
        conf.check_message(msg, '', True)
        return True
    except:
        conf.check_message(msg, '', False)
        return False


@conf
def CHECK_SHLIB_W_PYTHON(conf, msg):
    '''check if we need -undefined dynamic_lookup'''

    dir = find_config_dir(conf)

    env = conf.env

    snip = '''
#include <Python.h>
#include <crt_externs.h>
#define environ (*_NSGetEnviron())

static PyObject *ldb_module = NULL;
int foo(int v) {
    extern char **environ;
    environ[0] = 1;
    ldb_module = PyImport_ImportModule("ldb");
    return v * 2;
}'''
    return conf.check(features='cc cshlib',uselib='PYEMBED',fragment=snip,msg=msg)

# this one is quite complex, and should probably be broken up
# into several parts. I'd quite like to create a set of CHECK_COMPOUND()
# functions that make writing complex compound tests like this much easier
@conf
def CHECK_LIBRARY_SUPPORT(conf, rpath=False, version_script=False, msg=None):
    '''see if the platform supports building libraries'''

    if msg is None:
        if rpath:
            msg = "rpath library support"
        else:
            msg = "building library support"

    dir = find_config_dir(conf)

    bdir = os.path.join(dir, 'testbuild')
    if not os.path.exists(bdir):
        os.makedirs(bdir)

    env = conf.env

    subdir = os.path.join(dir, "libdir")

    os.makedirs(subdir)

    dest = open(os.path.join(subdir, 'lib1.c'), 'w')
    dest.write('int lib_func(void) { return 42; }\n')
    dest.close()

    dest = open(os.path.join(dir, 'main.c'), 'w')
    dest.write('int main(void) {return !(lib_func() == 42);}\n')
    dest.close()

    bld = Build.BuildContext()
    bld.log = conf.log
    bld.all_envs.update(conf.all_envs)
    bld.all_envs['default'] = env
    bld.lst_variants = bld.all_envs.keys()
    bld.load_dirs(dir, bdir)

    bld.rescan(bld.srcnode)

    ldflags = []
    if version_script:
        ldflags.append("-Wl,--version-script=%s/vscript" % bld.path.abspath())
        dest = open(os.path.join(dir,'vscript'), 'w')
        dest.write('TEST_1.0A2 { global: *; };\n')
        dest.close()

    bld(features='cc cshlib',
        source='libdir/lib1.c',
        target='libdir/lib1',
        ldflags=ldflags,
        name='lib1')

    o = bld(features='cc cprogram',
            source='main.c',
            target='prog1',
            uselib_local='lib1')

    if rpath:
        o.rpath=os.path.join(bdir, 'default/libdir')

    # compile the program
    try:
        bld.compile()
    except:
        conf.check_message(msg, '', False)
        return False

    # path for execution
    lastprog = o.link_task.outputs[0].abspath(env)

    if not rpath:
        if 'LD_LIBRARY_PATH' in os.environ:
            old_ld_library_path = os.environ['LD_LIBRARY_PATH']
        else:
            old_ld_library_path = None
        ADD_LD_LIBRARY_PATH(os.path.join(bdir, 'default/libdir'))

    # we need to run the program, try to get its result
    args = conf.SAMBA_CROSS_ARGS(msg=msg)
    proc = Utils.pproc.Popen([lastprog] + args, stdout=Utils.pproc.PIPE, stderr=Utils.pproc.PIPE)
    (out, err) = proc.communicate()
    w = conf.log.write
    w(str(out))
    w('\n')
    w(str(err))
    w('\nreturncode %r\n' % proc.returncode)
    ret = (proc.returncode == 0)

    if not rpath:
        os.environ['LD_LIBRARY_PATH'] = old_ld_library_path or ''

    conf.check_message(msg, '', ret)
    return ret



@conf
def CHECK_PERL_MANPAGE(conf, msg=None, section=None):
    '''work out what extension perl uses for manpages'''

    if msg is None:
        if section:
            msg = "perl man%s extension" % section
        else:
            msg = "perl manpage generation"

    conf.check_message_1(msg)

    dir = find_config_dir(conf)

    bdir = os.path.join(dir, 'testbuild')
    if not os.path.exists(bdir):
        os.makedirs(bdir)

    dest = open(os.path.join(bdir, 'Makefile.PL'), 'w')
    dest.write("""
use ExtUtils::MakeMaker;
WriteMakefile(
    'NAME'    => 'WafTest',
    'EXE_FILES' => [ 'WafTest' ]
);
""")
    dest.close()
    back = os.path.abspath('.')
    os.chdir(bdir)
    proc = Utils.pproc.Popen(['perl', 'Makefile.PL'],
                             stdout=Utils.pproc.PIPE,
                             stderr=Utils.pproc.PIPE)
    (out, err) = proc.communicate()
    os.chdir(back)

    ret = (proc.returncode == 0)
    if not ret:
        conf.check_message_2('not found', color='YELLOW')
        return

    if section:
        f = open(os.path.join(bdir,'Makefile'), 'r')
        man = f.read()
        f.close()
        m = re.search('MAN%sEXT\s+=\s+(\w+)' % section, man)
        if not m:
            conf.check_message_2('not found', color='YELLOW')
            return
        ext = m.group(1)
        conf.check_message_2(ext)
        return ext

    conf.check_message_2('ok')
    return True


@conf
def CHECK_COMMAND(conf, cmd, msg=None, define=None, on_target=True, boolean=False):
    '''run a command and return result'''
    if msg is None:
        msg = 'Checking %s' % ' '.join(cmd)
    conf.COMPOUND_START(msg)
    cmd = cmd[:]
    if on_target:
        cmd.extend(conf.SAMBA_CROSS_ARGS(msg=msg))
    try:
        ret = Utils.cmd_output(cmd)
    except:
        conf.COMPOUND_END(False)
        return False
    if boolean:
        conf.COMPOUND_END('ok')
        if define:
            conf.DEFINE(define, '1')
    else:
        ret = ret.strip()
        conf.COMPOUND_END(ret)
        if define:
            conf.DEFINE(define, ret, quote=True)
    return ret


@conf
def CHECK_UNAME(conf):
    '''setup SYSTEM_UNAME_* defines'''
    ret = True
    for v in "sysname machine release version".split():
        if not conf.CHECK_CODE('''
                               struct utsname n;
                               if (uname(&n) == -1) return -1;
                               printf("%%s", n.%s);
                               ''' % v,
                               define='SYSTEM_UNAME_%s' % v.upper(),
                               execute=True,
                               define_ret=True,
                               quote=True,
                               headers='sys/utsname.h',
                               local_include=False,
                               msg="Checking uname %s type" % v):
            ret = False
    return ret

@conf
def CHECK_INLINE(conf):
    '''check for the right value for inline'''
    conf.COMPOUND_START('Checking for inline')
    for i in ['inline', '__inline__', '__inline']:
        ret = conf.CHECK_CODE('''
        typedef int foo_t;
        static %s foo_t static_foo () {return 0; }
        %s foo_t foo () {return 0; }''' % (i, i),
                              define='INLINE_MACRO',
                              addmain=False,
                              link=False)
        if ret:
            if i != 'inline':
                conf.DEFINE('inline', i, quote=False)
            break
    if not ret:
        conf.COMPOUND_END(ret)
    else:
        conf.COMPOUND_END(i)
    return ret

@conf
def CHECK_XSLTPROC_MANPAGES(conf):
    '''check if xsltproc can run with the given stylesheets'''


    if not conf.CONFIG_SET('XSLTPROC'):
        conf.find_program('xsltproc', var='XSLTPROC')
    if not conf.CONFIG_SET('XSLTPROC'):
        return False

    s='http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl'
    conf.CHECK_COMMAND('%s --nonet %s 2> /dev/null' % (conf.env.XSLTPROC, s),
                             msg='Checking for stylesheet %s' % s,
                             define='XSLTPROC_MANPAGES', on_target=False,
                             boolean=True)