build: fixed uname output to be on target machine when cross compiling
[samba.git] / buildtools / wafsamba / samba_autoconf.py
1 # a waf tool to add autoconf-like macros to the configure section
2
3 import Build, os, Options, preproc, Logs
4 import string
5 from Configure import conf
6 from samba_utils import *
7 import samba_cross
8
9 missing_headers = set()
10
11 ####################################################
12 # some autoconf like helpers, to make the transition
13 # to waf a bit easier for those used to autoconf
14 # m4 files
15
16 @runonce
17 @conf
18 def DEFINE(conf, d, v, add_to_cflags=False, quote=False):
19     '''define a config option'''
20     conf.define(d, v, quote=quote)
21     if add_to_cflags:
22         conf.env.append_value('CCDEFINES', d + '=' + str(v))
23
24 def hlist_to_string(conf, headers=None):
25     '''convert a headers list to a set of #include lines'''
26     hdrs=''
27     hlist = conf.env.hlist
28     if headers:
29         hlist = hlist[:]
30         hlist.extend(TO_LIST(headers))
31     for h in hlist:
32         hdrs += '#include <%s>\n' % h
33     return hdrs
34
35
36 @conf
37 def COMPOUND_START(conf, msg):
38     '''start a compound test'''
39     def null_check_message_1(self,*k,**kw):
40         return
41     def null_check_message_2(self,*k,**kw):
42         return
43
44     v = getattr(conf.env, 'in_compound', [])
45     if v != [] and v != 0:
46         conf.env.in_compound = v + 1
47         return
48     conf.check_message_1(msg)
49     conf.saved_check_message_1 = conf.check_message_1
50     conf.check_message_1 = null_check_message_1
51     conf.saved_check_message_2 = conf.check_message_2
52     conf.check_message_2 = null_check_message_2
53     conf.env.in_compound = 1
54
55
56 @conf
57 def COMPOUND_END(conf, result):
58     '''start a compound test'''
59     conf.env.in_compound -= 1
60     if conf.env.in_compound != 0:
61         return
62     conf.check_message_1 = conf.saved_check_message_1
63     conf.check_message_2 = conf.saved_check_message_2
64     p = conf.check_message_2
65     if result == True:
66         p('ok ')
67     elif result == False:
68         p('not found', 'YELLOW')
69     else:
70         p(result)
71
72
73 @feature('nolink')
74 def nolink(self):
75     '''using the nolink type in conf.check() allows us to avoid
76        the link stage of a test, thus speeding it up for tests
77        that where linking is not needed'''
78     pass
79
80
81 def CHECK_HEADER(conf, h, add_headers=False, lib=None):
82     '''check for a header'''
83     if h in missing_headers:
84         return False
85     d = h.upper().replace('/', '_')
86     d = d.replace('.', '_')
87     d = 'HAVE_%s' % d
88     if CONFIG_SET(conf, d):
89         if add_headers:
90             if not h in conf.env.hlist:
91                 conf.env.hlist.append(h)
92         return True
93
94     (ccflags, ldflags) = library_flags(conf, lib)
95
96     hdrs = hlist_to_string(conf, headers=h)
97     ret = conf.check(fragment='%s\nint main(void) { return 0; }' % hdrs,
98                      type='nolink',
99                      execute=0,
100                      ccflags=ccflags,
101                      msg="Checking for header %s" % h)
102     if not ret:
103         missing_headers.add(h)
104         return False
105
106     conf.DEFINE(d, 1)
107     if add_headers and not h in conf.env.hlist:
108         conf.env.hlist.append(h)
109     return ret
110
111
112 @conf
113 def CHECK_HEADERS(conf, headers, add_headers=False, together=False, lib=None):
114     '''check for a list of headers
115
116     when together==True, then the headers accumulate within this test.
117     This is useful for interdependent headers
118     '''
119     ret = True
120     if not add_headers and together:
121         saved_hlist = conf.env.hlist[:]
122         set_add_headers = True
123     else:
124         set_add_headers = add_headers
125     for hdr in TO_LIST(headers):
126         if not CHECK_HEADER(conf, hdr, set_add_headers, lib=lib):
127             ret = False
128     if not add_headers and together:
129         conf.env.hlist = saved_hlist
130     return ret
131
132
133 def header_list(conf, headers=None, lib=None):
134     '''form a list of headers which exist, as a string'''
135     hlist=[]
136     if headers is not None:
137         for h in TO_LIST(headers):
138             if CHECK_HEADER(conf, h, add_headers=False, lib=lib):
139                 hlist.append(h)
140     return hlist_to_string(conf, headers=hlist)
141
142
143 @conf
144 def CHECK_TYPE(conf, t, alternate=None, headers=None, define=None, lib=None, msg=None):
145     '''check for a single type'''
146     if define is None:
147         define = 'HAVE_' + t.upper().replace(' ', '_')
148     if msg is None:
149         msg='Checking for %s' % t
150     ret = CHECK_CODE(conf, '%s _x' % t,
151                      define,
152                      execute=False,
153                      headers=headers,
154                      local_include=False,
155                      msg=msg,
156                      lib=lib,
157                      link=False)
158     if not ret and alternate:
159         conf.DEFINE(t, alternate)
160     return ret
161
162
163 @conf
164 def CHECK_TYPES(conf, list, headers=None, define=None, alternate=None, lib=None):
165     '''check for a list of types'''
166     ret = True
167     for t in TO_LIST(list):
168         if not CHECK_TYPE(conf, t, headers=headers,
169                           define=define, alternate=alternate, lib=lib):
170             ret = False
171     return ret
172
173
174 @conf
175 def CHECK_TYPE_IN(conf, t, headers=None, alternate=None, define=None):
176     '''check for a single type with a header'''
177     return CHECK_TYPE(conf, t, headers=headers, alternate=alternate, define=define)
178
179
180 @conf
181 def CHECK_VARIABLE(conf, v, define=None, always=False,
182                    headers=None, msg=None, lib=None):
183     '''check for a variable declaration (or define)'''
184     if define is None:
185         define = 'HAVE_%s' % v.upper()
186
187     if msg is None:
188         msg="Checking for variable %s" % v
189
190     return CHECK_CODE(conf,
191                       # we need to make sure the compiler doesn't
192                       # optimize it out...
193                       '''
194                       #ifndef %s
195                       void *_x; _x=(void *)&%s; return (int)_x;
196                       #endif
197                       return 0
198                       ''' % (v, v),
199                       execute=False,
200                       link=False,
201                       msg=msg,
202                       local_include=False,
203                       lib=lib,
204                       headers=headers,
205                       define=define,
206                       always=always)
207
208
209 @conf
210 def CHECK_DECLS(conf, vars, reverse=False, headers=None, always=False):
211     '''check a list of variable declarations, using the HAVE_DECL_xxx form
212        of define
213
214        When reverse==True then use HAVE_xxx_DECL instead of HAVE_DECL_xxx
215        '''
216     ret = True
217     for v in TO_LIST(vars):
218         if not reverse:
219             define='HAVE_DECL_%s' % v.upper()
220         else:
221             define='HAVE_%s_DECL' % v.upper()
222         if not CHECK_VARIABLE(conf, v,
223                               define=define,
224                               headers=headers,
225                               msg='Checking for declaration of %s' % v,
226                               always=always):
227             ret = False
228     return ret
229
230
231 def CHECK_FUNC(conf, f, link=True, lib=None, headers=None):
232     '''check for a function'''
233     define='HAVE_%s' % f.upper()
234
235     ret = False
236
237     conf.COMPOUND_START('Checking for %s' % f)
238
239     if link is None or link == True:
240         ret = CHECK_CODE(conf,
241                          # this is based on the autoconf strategy
242                          '''
243                          #define %s __fake__%s
244                          #ifdef HAVE_LIMITS_H
245                          # include <limits.h>
246                          #else
247                          # include <assert.h>
248                          #endif
249                          #undef %s
250                          #if defined __stub_%s || defined __stub___%s
251                          #error "bad glibc stub"
252                          #endif
253                          extern char %s();
254                          int main() { return %s(); }
255                          ''' % (f, f, f, f, f, f, f),
256                          execute=False,
257                          link=True,
258                          addmain=False,
259                          add_headers=False,
260                          define=define,
261                          local_include=False,
262                          lib=lib,
263                          headers=headers,
264                          msg='Checking for %s' % f)
265
266         if not ret:
267             ret = CHECK_CODE(conf,
268                              # it might be a macro
269                              # we need to make sure the compiler doesn't
270                              # optimize it out...
271                              'void *__x = (void *)%s; return (int)__x' % f,
272                              execute=False,
273                              link=True,
274                              addmain=True,
275                              add_headers=True,
276                              define=define,
277                              local_include=False,
278                              lib=lib,
279                              headers=headers,
280                              msg='Checking for macro %s' % f)
281
282     if not ret and (link is None or link == False):
283         ret = CHECK_VARIABLE(conf, f,
284                              define=define,
285                              headers=headers,
286                              msg='Checking for declaration of %s' % f)
287     conf.COMPOUND_END(ret)
288     return ret
289
290
291 @conf
292 def CHECK_FUNCS(conf, list, link=True, lib=None, headers=None):
293     '''check for a list of functions'''
294     ret = True
295     for f in TO_LIST(list):
296         if not CHECK_FUNC(conf, f, link=link, lib=lib, headers=headers):
297             ret = False
298     return ret
299
300
301 @conf
302 def CHECK_SIZEOF(conf, vars, headers=None, define=None):
303     '''check the size of a type'''
304     ret = True
305     for v in TO_LIST(vars):
306         v_define = define
307         if v_define is None:
308             v_define = 'SIZEOF_%s' % v.upper().replace(' ', '_')
309         if not CHECK_CODE(conf,
310                           'printf("%%u", (unsigned)sizeof(%s))' % v,
311                           define=v_define,
312                           execute=True,
313                           define_ret=True,
314                           quote=False,
315                           headers=headers,
316                           local_include=False,
317                           msg="Checking size of %s" % v):
318             ret = False
319     return ret
320
321
322
323 @conf
324 def CHECK_CODE(conf, code, define,
325                always=False, execute=False, addmain=True,
326                add_headers=True, mandatory=False,
327                headers=None, msg=None, cflags='', includes='# .',
328                local_include=True, lib=None, link=True,
329                define_ret=False, quote=False,
330                on_target=True):
331     '''check if some code compiles and/or runs'''
332
333     if CONFIG_SET(conf, define):
334         return True
335
336     if headers is not None:
337         CHECK_HEADERS(conf, headers=headers, lib=lib)
338
339     if add_headers:
340         hdrs = header_list(conf, headers=headers, lib=lib)
341     else:
342         hdrs = ''
343     if execute:
344         execute = 1
345     else:
346         execute = 0
347
348     if addmain:
349         fragment='#include "__confdefs.h"\n%s\n int main(void) { %s; return 0; }\n' % (hdrs, code)
350     else:
351         fragment='#include "__confdefs.h"\n%s\n%s\n' % (hdrs, code)
352
353     conf.write_config_header('__confdefs.h', top=True)
354
355     if msg is None:
356         msg="Checking for %s" % define
357
358     # include the directory containing __confdefs.h
359     cflags += ' -I../../default'
360
361     if local_include:
362         cflags += ' -I%s' % conf.curdir
363
364     if not link:
365         type='nolink'
366     else:
367         type='cprogram'
368
369     uselib = TO_LIST(lib)
370
371     (ccflags, ldflags) = library_flags(conf, uselib)
372
373     cflags = TO_LIST(cflags)
374     cflags.extend(ccflags)
375
376     if on_target:
377         exec_args = conf.SAMBA_CROSS_ARGS(msg=msg)
378     else:
379         exec_args = []
380
381     conf.COMPOUND_START(msg)
382
383     ret = conf.check(fragment=fragment,
384                      execute=execute,
385                      define_name = define,
386                      mandatory = mandatory,
387                      ccflags=cflags,
388                      ldflags=ldflags,
389                      includes=includes,
390                      uselib=uselib,
391                      type=type,
392                      msg=msg,
393                      quote=quote,
394                      exec_args=exec_args,
395                      define_ret=define_ret)
396     if not ret and CONFIG_SET(conf, define):
397         # sometimes conf.check() returns false, but it
398         # sets the define. Maybe a waf bug?
399         ret = True
400     if ret:
401         if not define_ret:
402             conf.DEFINE(define, 1)
403             conf.COMPOUND_END(True)
404         else:
405             conf.COMPOUND_END(conf.env[define])
406         return True
407     if always:
408         conf.DEFINE(define, 0)
409     conf.COMPOUND_END(False)
410     return False
411
412
413
414 @conf
415 def CHECK_STRUCTURE_MEMBER(conf, structname, member,
416                            always=False, define=None, headers=None):
417     '''check for a structure member'''
418     if define is None:
419         define = 'HAVE_%s' % member.upper()
420     return CHECK_CODE(conf,
421                       '%s s; void *_x; _x=(void *)&s.%s' % (structname, member),
422                       define,
423                       execute=False,
424                       link=False,
425                       always=always,
426                       headers=headers,
427                       local_include=False,
428                       msg="Checking for member %s in %s" % (member, structname))
429
430
431 @conf
432 def CHECK_CFLAGS(conf, cflags):
433     '''check if the given cflags are accepted by the compiler
434     '''
435     return conf.check(fragment='int main(void) { return 0; }\n',
436                       execute=0,
437                       type='nolink',
438                       ccflags=cflags,
439                       msg="Checking compiler accepts %s" % cflags)
440
441
442 @conf
443 def CONFIG_SET(conf, option):
444     '''return True if a configuration option was found'''
445     return (option in conf.env) and (conf.env[option] != ())
446 Build.BuildContext.CONFIG_SET = CONFIG_SET
447
448
449 def library_flags(conf, libs):
450     '''work out flags from pkg_config'''
451     ccflags = []
452     ldflags = []
453     for lib in TO_LIST(libs):
454         inc_path = None
455         inc_path = getattr(conf.env, 'CPPPATH_%s' % lib.upper(), [])
456         lib_path = getattr(conf.env, 'LIBPATH_%s' % lib.upper(), [])
457         for i in inc_path:
458             ccflags.append('-I%s' % i)
459         for l in lib_path:
460             ldflags.append('-L%s' % l)
461     return (ccflags, ldflags)
462
463
464 @conf
465 def CHECK_LIB(conf, libs, mandatory=False, empty_decl=True):
466     '''check if a set of libraries exist'''
467
468     liblist  = TO_LIST(libs)
469     ret = True
470     for lib in liblist[:]:
471         if GET_TARGET_TYPE(conf, lib) == 'SYSLIB':
472             continue
473
474         (ccflags, ldflags) = library_flags(conf, lib)
475
476         if not conf.check(lib=lib, uselib_store=lib, ccflags=ccflags, ldflags=ldflags):
477             if mandatory:
478                 Logs.error("Mandatory library '%s' not found for functions '%s'" % (lib, list))
479                 sys.exit(1)
480             if empty_decl:
481                 # if it isn't a mandatory library, then remove it from dependency lists
482                 SET_TARGET_TYPE(conf, lib, 'EMPTY')
483             ret = False
484         else:
485             conf.define('HAVE_LIB%s' % lib.upper().replace('-','_'), 1)
486             conf.env['LIB_' + lib.upper()] = lib
487             LOCAL_CACHE_SET(conf, 'TARGET_TYPE', lib, 'SYSLIB')
488
489     return ret
490
491
492
493 @conf
494 def CHECK_FUNCS_IN(conf, list, library, mandatory=False, checklibc=False,
495                    headers=None, link=True, empty_decl=True):
496     """
497     check that the functions in 'list' are available in 'library'
498     if they are, then make that library available as a dependency
499
500     if the library is not available and mandatory==True, then
501     raise an error.
502
503     If the library is not available and mandatory==False, then
504     add the library to the list of dependencies to remove from
505     build rules
506
507     optionally check for the functions first in libc
508     """
509     remaining = TO_LIST(list)
510     liblist   = TO_LIST(library)
511
512     # check if some already found
513     for f in remaining[:]:
514         if CONFIG_SET(conf, 'HAVE_%s' % f.upper()):
515             remaining.remove(f)
516
517     # see if the functions are in libc
518     if checklibc:
519         for f in remaining[:]:
520             if CHECK_FUNC(conf, f, link=True, headers=headers):
521                 remaining.remove(f)
522
523     if remaining == []:
524         for lib in liblist:
525             if GET_TARGET_TYPE(conf, lib) != 'SYSLIB' and empty_decl:
526                 SET_TARGET_TYPE(conf, lib, 'EMPTY')
527         return True
528
529     conf.CHECK_LIB(liblist, empty_decl=empty_decl)
530     for lib in liblist[:]:
531         if not GET_TARGET_TYPE(conf, lib) == 'SYSLIB':
532             if mandatory:
533                 Logs.error("Mandatory library '%s' not found for functions '%s'" % (lib, list))
534                 sys.exit(1)
535             # if it isn't a mandatory library, then remove it from dependency lists
536             liblist.remove(lib)
537             continue
538
539     ret = True
540     for f in remaining:
541         if not CHECK_FUNC(conf, f, lib=' '.join(liblist), headers=headers, link=link):
542             ret = False
543
544     return ret
545
546
547 @conf
548 def IN_LAUNCH_DIR(conf):
549     '''return True if this rule is being run from the launch directory'''
550     return os.path.realpath(conf.curdir) == os.path.realpath(Options.launch_dir)
551 Options.Handler.IN_LAUNCH_DIR = IN_LAUNCH_DIR
552
553
554 @conf
555 def SAMBA_CONFIG_H(conf, path=None):
556     '''write out config.h in the right directory'''
557     # we don't want to produce a config.h in places like lib/replace
558     # when we are building projects that depend on lib/replace
559     if not IN_LAUNCH_DIR(conf):
560         return
561
562     if Options.options.developer:
563         # we add these here to ensure that -Wstrict-prototypes is not set during configure
564         conf.ADD_CFLAGS('-Wall -g -Wshadow -Wstrict-prototypes -Wpointer-arith -Wcast-qual -Wcast-align -Wwrite-strings -Werror-implicit-function-declaration -Wformat=2 -Wno-format-y2k',
565                         testflags=True)
566
567     if Options.options.picky_developer:
568         conf.ADD_CFLAGS('-Werror', testflags=True)
569
570     if Options.options.fatal_errors:
571         conf.ADD_CFLAGS('-Wfatal-errors', testflags=True)
572
573     if Options.options.pedantic:
574         conf.ADD_CFLAGS('-W', testflags=True)
575
576     if path is None:
577         conf.write_config_header('config.h', top=True)
578     else:
579         conf.write_config_header(path)
580     conf.SAMBA_CROSS_CHECK_COMPLETE()
581
582
583 @conf
584 def CONFIG_PATH(conf, name, default):
585     '''setup a configurable path'''
586     if not name in conf.env:
587         if default[0] == '/':
588             conf.env[name] = default
589         else:
590             conf.env[name] = conf.env['PREFIX'] + default
591
592 @conf
593 def ADD_CFLAGS(conf, flags, testflags=False):
594     '''add some CFLAGS to the command line
595        optionally set testflags to ensure all the flags work
596     '''
597     if testflags:
598         ok_flags=[]
599         for f in flags.split():
600             if CHECK_CFLAGS(conf, f):
601                 ok_flags.append(f)
602         flags = ok_flags
603     if not 'EXTRA_CFLAGS' in conf.env:
604         conf.env['EXTRA_CFLAGS'] = []
605     conf.env['EXTRA_CFLAGS'].extend(TO_LIST(flags))
606
607
608
609 @conf
610 def ADD_EXTRA_INCLUDES(conf, includes):
611     '''add some extra include directories to all builds'''
612     if not 'EXTRA_INCLUDES' in conf.env:
613         conf.env['EXTRA_INCLUDES'] = []
614     conf.env['EXTRA_INCLUDES'].extend(TO_LIST(includes))
615
616
617
618 def CURRENT_CFLAGS(bld, target, cflags, hide_symbols=False):
619     '''work out the current flags. local flags are added first'''
620     if not 'EXTRA_CFLAGS' in bld.env:
621         list = []
622     else:
623         list = bld.env['EXTRA_CFLAGS'];
624     ret = TO_LIST(cflags)
625     ret.extend(list)
626     if hide_symbols and bld.env.HAVE_VISIBILITY_ATTR:
627         ret.append('-fvisibility=hidden')
628     return ret
629
630
631 @conf
632 def CHECK_CC_ENV(conf):
633     """trim whitespaces from 'CC'.
634     The build farm sometimes puts a space at the start"""
635     if os.environ.get('CC'):
636         conf.env.CC = TO_LIST(os.environ.get('CC'))
637         if len(conf.env.CC) == 1:
638             # make for nicer logs if just a single command
639             conf.env.CC = conf.env.CC[0]
640
641
642 @conf
643 def SETUP_CONFIGURE_CACHE(conf, enable):
644     '''enable/disable cache of configure results'''
645     if enable:
646         # when -C is chosen, we will use a private cache and will
647         # not look into system includes. This roughtly matches what
648         # autoconf does with -C
649         cache_path = os.path.join(conf.blddir, '.confcache')
650         mkdir_p(cache_path)
651         Options.cache_global = os.environ['WAFCACHE'] = cache_path
652     else:
653         # when -C is not chosen we will not cache configure checks
654         # We set the recursion limit low to prevent waf from spending
655         # a lot of time on the signatures of the files.
656         Options.cache_global = os.environ['WAFCACHE'] = ''
657         preproc.recursion_limit = 1
658     # in either case we don't need to scan system includes
659     preproc.go_absolute = False