wafsamba: fix CHECK_MAKEFLAGS() with waf 2.0.8
[nivanova/samba-autobuild/.git] / buildtools / wafsamba / samba_utils.py
1 # a waf tool to add autoconf-like macros to the configure section
2 # and for SAMBA_ macros for building libraries, binaries etc
3
4 import os, sys, re, fnmatch, shlex, inspect
5 from optparse import SUPPRESS_HELP
6 from waflib import Build, Options, Utils, Task, Logs, Configure, Errors, Context
7 from waflib import Scripting
8 from waflib.TaskGen import feature, before, after
9 from waflib.Configure import ConfigurationContext
10 from waflib.Logs import debug
11 from waflib import ConfigSet
12 from waflib.Build import CACHE_SUFFIX
13
14 # TODO: make this a --option
15 LIB_PATH="shared"
16
17
18 # sigh, python octal constants are a mess
19 MODE_644 = int('644', 8)
20 MODE_755 = int('755', 8)
21
22 def conf(f):
23     # override in order to propagate the argument "mandatory"
24     def fun(*k, **kw):
25         mandatory = True
26         if 'mandatory' in kw:
27             mandatory = kw['mandatory']
28             del kw['mandatory']
29
30         try:
31             return f(*k, **kw)
32         except Errors.ConfigurationError:
33             if mandatory:
34                 raise
35
36     fun.__name__ = f.__name__
37     if 'mandatory' in inspect.getsource(f):
38         fun = f
39
40     setattr(Configure.ConfigurationContext, f.__name__, fun)
41     setattr(Build.BuildContext, f.__name__, fun)
42     return f
43 Configure.conf = conf
44 Configure.conftest = conf
45
46 @conf
47 def SET_TARGET_TYPE(ctx, target, value):
48     '''set the target type of a target'''
49     cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
50     if target in cache and cache[target] != 'EMPTY':
51         Logs.error("ERROR: Target '%s' in directory %s re-defined as %s - was %s" % (target, ctx.path.abspath(), value, cache[target]))
52         sys.exit(1)
53     LOCAL_CACHE_SET(ctx, 'TARGET_TYPE', target, value)
54     debug("task_gen: Target '%s' created of type '%s' in %s" % (target, value, ctx.path.abspath()))
55     return True
56
57
58 def GET_TARGET_TYPE(ctx, target):
59     '''get target type from cache'''
60     cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
61     if not target in cache:
62         return None
63     return cache[target]
64
65
66 def ADD_LD_LIBRARY_PATH(path):
67     '''add something to LD_LIBRARY_PATH'''
68     if 'LD_LIBRARY_PATH' in os.environ:
69         oldpath = os.environ['LD_LIBRARY_PATH']
70     else:
71         oldpath = ''
72     newpath = oldpath.split(':')
73     if not path in newpath:
74         newpath.append(path)
75         os.environ['LD_LIBRARY_PATH'] = ':'.join(newpath)
76
77
78 def needs_private_lib(bld, target):
79     '''return True if a target links to a private library'''
80     for lib in getattr(target, "final_libs", []):
81         t = bld.get_tgen_by_name(lib)
82         if t and getattr(t, 'private_library', False):
83             return True
84     return False
85
86
87 def install_rpath(target):
88     '''the rpath value for installation'''
89     bld = target.bld
90     bld.env['RPATH'] = []
91     ret = set()
92     if bld.env.RPATH_ON_INSTALL:
93         ret.add(bld.EXPAND_VARIABLES(bld.env.LIBDIR))
94     if bld.env.RPATH_ON_INSTALL_PRIVATE and needs_private_lib(bld, target):
95         ret.add(bld.EXPAND_VARIABLES(bld.env.PRIVATELIBDIR))
96     return list(ret)
97
98
99 def build_rpath(bld):
100     '''the rpath value for build'''
101     rpaths = [os.path.normpath('%s/%s' % (bld.env.BUILD_DIRECTORY, d)) for d in ("shared", "shared/private")]
102     bld.env['RPATH'] = []
103     if bld.env.RPATH_ON_BUILD:
104         return rpaths
105     for rpath in rpaths:
106         ADD_LD_LIBRARY_PATH(rpath)
107     return []
108
109
110 @conf
111 def LOCAL_CACHE(ctx, name):
112     '''return a named build cache dictionary, used to store
113        state inside other functions'''
114     if name in ctx.env:
115         return ctx.env[name]
116     ctx.env[name] = {}
117     return ctx.env[name]
118
119
120 @conf
121 def LOCAL_CACHE_SET(ctx, cachename, key, value):
122     '''set a value in a local cache'''
123     cache = LOCAL_CACHE(ctx, cachename)
124     cache[key] = value
125
126
127 @conf
128 def ASSERT(ctx, expression, msg):
129     '''a build assert call'''
130     if not expression:
131         raise Errors.WafError("ERROR: %s\n" % msg)
132 Build.BuildContext.ASSERT = ASSERT
133
134
135 def SUBDIR(bld, subdir, list):
136     '''create a list of files by pre-pending each with a subdir name'''
137     ret = ''
138     for l in TO_LIST(list):
139         ret = ret + os.path.normpath(os.path.join(subdir, l)) + ' '
140     return ret
141 Build.BuildContext.SUBDIR = SUBDIR
142
143
144 def dict_concat(d1, d2):
145     '''concatenate two dictionaries d1 += d2'''
146     for t in d2:
147         if t not in d1:
148             d1[t] = d2[t]
149
150 def ADD_COMMAND(opt, name, function):
151     '''add a new top level command to waf'''
152     Context.g_module.__dict__[name] = function
153     opt.name = function
154 Options.OptionsContext.ADD_COMMAND = ADD_COMMAND
155
156
157 @feature('c', 'cc', 'cshlib', 'cprogram')
158 @before('apply_core','exec_rule')
159 def process_depends_on(self):
160     '''The new depends_on attribute for build rules
161        allow us to specify a dependency on output from
162        a source generation rule'''
163     if getattr(self , 'depends_on', None):
164         lst = self.to_list(self.depends_on)
165         for x in lst:
166             y = self.bld.get_tgen_by_name(x)
167             self.bld.ASSERT(y is not None, "Failed to find dependency %s of %s" % (x, self.name))
168             y.post()
169             if getattr(y, 'more_includes', None):
170                   self.includes += " " + y.more_includes
171
172
173 os_path_relpath = getattr(os.path, 'relpath', None)
174 if os_path_relpath is None:
175     # Python < 2.6 does not have os.path.relpath, provide a replacement
176     # (imported from Python2.6.5~rc2)
177     def os_path_relpath(path, start):
178         """Return a relative version of a path"""
179         start_list = os.path.abspath(start).split("/")
180         path_list = os.path.abspath(path).split("/")
181
182         # Work out how much of the filepath is shared by start and path.
183         i = len(os.path.commonprefix([start_list, path_list]))
184
185         rel_list = ['..'] * (len(start_list)-i) + path_list[i:]
186         if not rel_list:
187             return start
188         return os.path.join(*rel_list)
189
190
191 def unique_list(seq):
192     '''return a uniquified list in the same order as the existing list'''
193     seen = {}
194     result = []
195     for item in seq:
196         if item in seen: continue
197         seen[item] = True
198         result.append(item)
199     return result
200
201
202 def TO_LIST(str, delimiter=None):
203     '''Split a list, preserving quoted strings and existing lists'''
204     if str is None:
205         return []
206     if isinstance(str, list):
207         # we need to return a new independent list...
208         return list(str)
209     if len(str) == 0:
210         return []
211     lst = str.split(delimiter)
212     # the string may have had quotes in it, now we
213     # check if we did have quotes, and use the slower shlex
214     # if we need to
215     for e in lst:
216         if e[0] == '"':
217             return shlex.split(str)
218     return lst
219
220
221 def subst_vars_error(string, env):
222     '''substitute vars, throw an error if a variable is not defined'''
223     lst = re.split('(\$\{\w+\})', string)
224     out = []
225     for v in lst:
226         if re.match('\$\{\w+\}', v):
227             vname = v[2:-1]
228             if not vname in env:
229                 raise KeyError("Failed to find variable %s in %s in env %s <%s>" % (vname, string, env.__class__, str(env)))
230             v = env[vname]
231             if isinstance(v, list):
232                 v = ' '.join(v)
233         out.append(v)
234     return ''.join(out)
235
236
237 @conf
238 def SUBST_ENV_VAR(ctx, varname):
239     '''Substitute an environment variable for any embedded variables'''
240     return subst_vars_error(ctx.env[varname], ctx.env)
241 Build.BuildContext.SUBST_ENV_VAR = SUBST_ENV_VAR
242
243
244 def recursive_dirlist(dir, relbase, pattern=None):
245     '''recursive directory list'''
246     ret = []
247     for f in os.listdir(dir):
248         f2 = dir + '/' + f
249         if os.path.isdir(f2):
250             ret.extend(recursive_dirlist(f2, relbase))
251         else:
252             if pattern and not fnmatch.fnmatch(f, pattern):
253                 continue
254             ret.append(os_path_relpath(f2, relbase))
255     return ret
256
257
258 def mkdir_p(dir):
259     '''like mkdir -p'''
260     if not dir:
261         return
262     if dir.endswith("/"):
263         mkdir_p(dir[:-1])
264         return
265     if os.path.isdir(dir):
266         return
267     mkdir_p(os.path.dirname(dir))
268     os.mkdir(dir)
269
270
271 def SUBST_VARS_RECURSIVE(string, env):
272     '''recursively expand variables'''
273     if string is None:
274         return string
275     limit=100
276     while (string.find('${') != -1 and limit > 0):
277         string = subst_vars_error(string, env)
278         limit -= 1
279     return string
280
281
282 @conf
283 def EXPAND_VARIABLES(ctx, varstr, vars=None):
284     '''expand variables from a user supplied dictionary
285
286     This is most useful when you pass vars=locals() to expand
287     all your local variables in strings
288     '''
289
290     if isinstance(varstr, list):
291         ret = []
292         for s in varstr:
293             ret.append(EXPAND_VARIABLES(ctx, s, vars=vars))
294         return ret
295
296     if not isinstance(varstr, str):
297         return varstr
298
299     env = ConfigSet.ConfigSet()
300     ret = varstr
301     # substitute on user supplied dict if avaiilable
302     if vars is not None:
303         for v in vars.keys():
304             env[v] = vars[v]
305         ret = SUBST_VARS_RECURSIVE(ret, env)
306
307     # if anything left, subst on the environment as well
308     if ret.find('${') != -1:
309         ret = SUBST_VARS_RECURSIVE(ret, ctx.env)
310     # make sure there is nothing left. Also check for the common
311     # typo of $( instead of ${
312     if ret.find('${') != -1 or ret.find('$(') != -1:
313         Logs.error('Failed to substitute all variables in varstr=%s' % ret)
314         sys.exit(1)
315     return ret
316 Build.BuildContext.EXPAND_VARIABLES = EXPAND_VARIABLES
317
318
319 def RUN_COMMAND(cmd,
320                 env=None,
321                 shell=False):
322     '''run a external command, return exit code or signal'''
323     if env:
324         cmd = SUBST_VARS_RECURSIVE(cmd, env)
325
326     status = os.system(cmd)
327     if os.WIFEXITED(status):
328         return os.WEXITSTATUS(status)
329     if os.WIFSIGNALED(status):
330         return - os.WTERMSIG(status)
331     Logs.error("Unknown exit reason %d for command: %s" % (status, cmd))
332     return -1
333
334
335 def RUN_PYTHON_TESTS(testfiles, pythonpath=None, extra_env=None):
336     env = LOAD_ENVIRONMENT()
337     if pythonpath is None:
338         pythonpath = os.path.join(Context.g_module.out, 'python')
339     result = 0
340     for interp in env.python_interpreters:
341         if not isinstance(interp, str):
342             interp = ' '.join(interp)
343         for testfile in testfiles:
344             cmd = "PYTHONPATH=%s %s %s" % (pythonpath, interp, testfile)
345             if extra_env:
346                 for key, value in extra_env.items():
347                     cmd = "%s=%s %s" % (key, value, cmd)
348             print('Running Python test with %s: %s' % (interp, testfile))
349             ret = RUN_COMMAND(cmd)
350             if ret:
351                 print('Python test failed: %s' % cmd)
352                 result = ret
353     return result
354
355
356 # make sure we have md5. some systems don't have it
357 try:
358     from hashlib import md5
359     # Even if hashlib.md5 exists, it may be unusable.
360     # Try to use MD5 function. In FIPS mode this will cause an exception
361     # and we'll get to the replacement code
362     foo = md5(b'abcd')
363 except:
364     try:
365         import md5
366         # repeat the same check here, mere success of import is not enough.
367         # Try to use MD5 function. In FIPS mode this will cause an exception
368         foo = md5.md5(b'abcd')
369     except:
370         Context.SIG_NIL = hash('abcd')
371         class replace_md5(object):
372             def __init__(self):
373                 self.val = None
374             def update(self, val):
375                 self.val = hash((self.val, val))
376             def digest(self):
377                 return str(self.val)
378             def hexdigest(self):
379                 return self.digest().encode('hex')
380         def replace_h_file(filename):
381             f = open(filename, 'rb')
382             m = replace_md5()
383             while (filename):
384                 filename = f.read(100000)
385                 m.update(filename)
386             f.close()
387             return m.digest()
388         Utils.md5 = replace_md5
389         Task.md5 = replace_md5
390         Utils.h_file = replace_h_file
391
392
393 def LOAD_ENVIRONMENT():
394     '''load the configuration environment, allowing access to env vars
395        from new commands'''
396     env = ConfigSet.ConfigSet()
397     try:
398         p = os.path.join(Context.g_module.out, 'c4che/default'+CACHE_SUFFIX)
399         env.load(p)
400     except (OSError, IOError):
401         pass
402     return env
403
404
405 def IS_NEWER(bld, file1, file2):
406     '''return True if file1 is newer than file2'''
407     curdir = bld.path.abspath()
408     t1 = os.stat(os.path.join(curdir, file1)).st_mtime
409     t2 = os.stat(os.path.join(curdir, file2)).st_mtime
410     return t1 > t2
411 Build.BuildContext.IS_NEWER = IS_NEWER
412
413
414 @conf
415 def RECURSE(ctx, directory):
416     '''recurse into a directory, relative to the curdir or top level'''
417     try:
418         visited_dirs = ctx.visited_dirs
419     except AttributeError:
420         visited_dirs = ctx.visited_dirs = set()
421     d = os.path.join(ctx.path.abspath(), directory)
422     if os.path.exists(d):
423         abspath = os.path.abspath(d)
424     else:
425         abspath = os.path.abspath(os.path.join(Context.g_module.top, directory))
426     ctxclass = ctx.__class__.__name__
427     key = ctxclass + ':' + abspath
428     if key in visited_dirs:
429         # already done it
430         return
431     visited_dirs.add(key)
432     relpath = os_path_relpath(abspath, ctx.path.abspath())
433     if ctxclass in ['tmp', 'OptionsContext', 'ConfigurationContext', 'BuildContext']:
434         return ctx.recurse(relpath)
435     if 'waflib.extras.compat15' in sys.modules:
436         return ctx.recurse(relpath)
437     Logs.error('Unknown RECURSE context class: {}'.format(ctxclass))
438     raise
439 Options.OptionsContext.RECURSE = RECURSE
440 Build.BuildContext.RECURSE = RECURSE
441
442
443 def CHECK_MAKEFLAGS(options):
444     '''check for MAKEFLAGS environment variable in case we are being
445     called from a Makefile try to honor a few make command line flags'''
446     if not 'WAF_MAKE' in os.environ:
447         return
448     makeflags = os.environ.get('MAKEFLAGS')
449     if makeflags is None:
450         makeflags = ""
451     jobs_set = False
452     jobs = None
453     # we need to use shlex.split to cope with the escaping of spaces
454     # in makeflags
455     for opt in shlex.split(makeflags):
456         # options can come either as -x or as x
457         if opt[0:2] == 'V=':
458             options.verbose = Logs.verbose = int(opt[2:])
459             if Logs.verbose > 0:
460                 Logs.zones = ['runner']
461             if Logs.verbose > 2:
462                 Logs.zones = ['*']
463         elif opt[0].isupper() and opt.find('=') != -1:
464             # this allows us to set waf options on the make command line
465             # for example, if you do "make FOO=blah", then we set the
466             # option 'FOO' in Options.options, to blah. If you look in wafsamba/wscript
467             # you will see that the command line accessible options have their dest=
468             # set to uppercase, to allow for passing of options from make in this way
469             # this is also how "make test TESTS=testpattern" works, and
470             # "make VERBOSE=1" as well as things like "make SYMBOLCHECK=1"
471             loc = opt.find('=')
472             setattr(options, opt[0:loc], opt[loc+1:])
473         elif opt[0] != '-':
474             for v in opt:
475                 if re.search(r'j[0-9]*$', v):
476                     jobs_set = True
477                     jobs = opt.strip('j')
478                 elif v == 'k':
479                     options.keep = True
480         elif re.search(r'-j[0-9]*$', opt):
481             jobs_set = True
482             jobs = opt.strip('-j')
483         elif opt == '-k':
484             options.keep = True
485     if not jobs_set:
486         # default to one job
487         options.jobs = 1
488     elif jobs_set and jobs:
489         options.jobs = int(jobs)
490
491 waflib_options_parse_cmd_args = Options.OptionsContext.parse_cmd_args
492 def wafsamba_options_parse_cmd_args(self, _args=None, cwd=None, allow_unknown=False):
493     (options, commands, envvars) = \
494         waflib_options_parse_cmd_args(self,
495                                       _args=_args,
496                                       cwd=cwd,
497                                       allow_unknown=allow_unknown)
498     CHECK_MAKEFLAGS(options)
499     return options, commands, envvars
500 Options.OptionsContext.parse_cmd_args = wafsamba_options_parse_cmd_args
501
502 option_groups = {}
503
504 def option_group(opt, name):
505     '''find or create an option group'''
506     global option_groups
507     if name in option_groups:
508         return option_groups[name]
509     gr = opt.add_option_group(name)
510     option_groups[name] = gr
511     return gr
512 Options.OptionsContext.option_group = option_group
513
514
515 def save_file(filename, contents, create_dir=False):
516     '''save data to a file'''
517     if create_dir:
518         mkdir_p(os.path.dirname(filename))
519     try:
520         f = open(filename, 'w')
521         f.write(contents)
522         f.close()
523     except:
524         return False
525     return True
526
527
528 def load_file(filename):
529     '''return contents of a file'''
530     try:
531         f = open(filename, 'r')
532         r = f.read()
533         f.close()
534     except:
535         return None
536     return r
537
538
539 def reconfigure(ctx):
540     '''rerun configure if necessary'''
541     if not os.path.exists(".lock-wscript"):
542         raise Errors.WafError('configure has not been run')
543     import samba_wildcard
544     bld = samba_wildcard.fake_build_environment()
545     Configure.autoconfig = True
546     Scripting.check_configured(bld)
547
548
549 def map_shlib_extension(ctx, name, python=False):
550     '''map a filename with a shared library extension of .so to the real shlib name'''
551     if name is None:
552         return None
553     if name[-1:].isdigit():
554         # some libraries have specified versions in the wscript rule
555         return name
556     (root1, ext1) = os.path.splitext(name)
557     if python:
558         return ctx.env.pyext_PATTERN % root1
559     else:
560         (root2, ext2) = os.path.splitext(ctx.env.cshlib_PATTERN)
561     return root1+ext2
562 Build.BuildContext.map_shlib_extension = map_shlib_extension
563
564 def apply_pattern(filename, pattern):
565     '''apply a filename pattern to a filename that may have a directory component'''
566     dirname = os.path.dirname(filename)
567     if not dirname:
568         return pattern % filename
569     basename = os.path.basename(filename)
570     return os.path.join(dirname, pattern % basename)
571
572 def make_libname(ctx, name, nolibprefix=False, version=None, python=False):
573     """make a library filename
574          Options:
575               nolibprefix: don't include the lib prefix
576               version    : add a version number
577               python     : if we should use python module name conventions"""
578
579     if python:
580         libname = apply_pattern(name, ctx.env.pyext_PATTERN)
581     else:
582         libname = apply_pattern(name, ctx.env.cshlib_PATTERN)
583     if nolibprefix and libname[0:3] == 'lib':
584         libname = libname[3:]
585     if version:
586         if version[0] == '.':
587             version = version[1:]
588         (root, ext) = os.path.splitext(libname)
589         if ext == ".dylib":
590             # special case - version goes before the prefix
591             libname = "%s.%s%s" % (root, version, ext)
592         else:
593             libname = "%s%s.%s" % (root, ext, version)
594     return libname
595 Build.BuildContext.make_libname = make_libname
596
597
598 def get_tgt_list(bld):
599     '''return a list of build objects for samba'''
600
601     targets = LOCAL_CACHE(bld, 'TARGET_TYPE')
602
603     # build a list of task generators we are interested in
604     tgt_list = []
605     for tgt in targets:
606         type = targets[tgt]
607         if not type in ['SUBSYSTEM', 'MODULE', 'BINARY', 'LIBRARY', 'ASN1', 'PYTHON']:
608             continue
609         t = bld.get_tgen_by_name(tgt)
610         if t is None:
611             Logs.error("Target %s of type %s has no task generator" % (tgt, type))
612             sys.exit(1)
613         tgt_list.append(t)
614     return tgt_list
615
616 from waflib.Context import WSCRIPT_FILE
617 def PROCESS_SEPARATE_RULE(self, rule):
618     ''' cause waf to process additional script based on `rule'.
619         You should have file named wscript_<stage>_rule in the current directory
620         where stage is either 'configure' or 'build'
621     '''
622     stage = ''
623     if isinstance(self, Configure.ConfigurationContext):
624         stage = 'configure'
625     elif isinstance(self, Build.BuildContext):
626         stage = 'build'
627     file_path = os.path.join(self.path.abspath(), WSCRIPT_FILE+'_'+stage+'_'+rule)
628     node = self.root.find_node(file_path)
629     if node:
630         try:
631             cache = self.recurse_cache
632         except AttributeError:
633             cache = self.recurse_cache = {}
634         if node not in cache:
635             cache[node] = True
636             self.pre_recurse(node)
637             try:
638                 function_code = node.read('rU', None)
639                 exec(compile(function_code, node.abspath(), 'exec'), self.exec_dict)
640             finally:
641                 self.post_recurse(node)
642
643 Build.BuildContext.PROCESS_SEPARATE_RULE = PROCESS_SEPARATE_RULE
644 ConfigurationContext.PROCESS_SEPARATE_RULE = PROCESS_SEPARATE_RULE
645
646 def AD_DC_BUILD_IS_ENABLED(self):
647     if self.CONFIG_SET('AD_DC_BUILD_IS_ENABLED'):
648         return True
649     return False
650
651 Build.BuildContext.AD_DC_BUILD_IS_ENABLED = AD_DC_BUILD_IS_ENABLED
652
653 @feature('cprogram', 'cshlib', 'cstaticlib')
654 @after('apply_lib_vars')
655 @before('apply_obj_vars')
656 def samba_before_apply_obj_vars(self):
657     """before apply_obj_vars for uselib, this removes the standard paths"""
658
659     def is_standard_libpath(env, path):
660         for _path in env.STANDARD_LIBPATH:
661             if _path == os.path.normpath(path):
662                 return True
663         return False
664
665     v = self.env
666
667     for i in v['RPATH']:
668         if is_standard_libpath(v, i):
669             v['RPATH'].remove(i)
670
671     for i in v['LIBPATH']:
672         if is_standard_libpath(v, i):
673             v['LIBPATH'].remove(i)
674
675 def samba_add_onoff_option(opt, option, help=(), dest=None, default=True,
676                            with_name="with", without_name="without"):
677     if default is None:
678         default_str = "auto"
679     elif default is True:
680         default_str = "yes"
681     elif default is False:
682         default_str = "no"
683     else:
684         default_str = str(default)
685
686     if help == ():
687         help = ("Build with %s support (default=%s)" % (option, default_str))
688     if dest is None:
689         dest = "with_%s" % option.replace('-', '_')
690
691     with_val = "--%s-%s" % (with_name, option)
692     without_val = "--%s-%s" % (without_name, option)
693
694     opt.add_option(with_val, help=help, action="store_true", dest=dest,
695                    default=default)
696     opt.add_option(without_val, help=SUPPRESS_HELP, action="store_false",
697                    dest=dest)
698 Options.OptionsContext.samba_add_onoff_option = samba_add_onoff_option