1 # a waf tool to add autoconf-like macros to the configure section
2 # and for SAMBA_ macros for building libraries, binaries etc
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
14 # TODO: make this a --option
18 # sigh, python octal constants are a mess
19 MODE_644 = int('644', 8)
20 MODE_755 = int('755', 8)
23 # override in order to propagate the argument "mandatory"
27 mandatory = kw['mandatory']
32 except Errors.ConfigurationError:
36 fun.__name__ = f.__name__
37 if 'mandatory' in inspect.getsource(f):
40 setattr(Configure.ConfigurationContext, f.__name__, fun)
41 setattr(Build.BuildContext, f.__name__, fun)
44 Configure.conftest = 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]))
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()))
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:
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']
72 newpath = oldpath.split(':')
73 if not path in newpath:
75 os.environ['LD_LIBRARY_PATH'] = ':'.join(newpath)
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):
87 def install_rpath(target):
88 '''the rpath value for installation'''
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))
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:
106 ADD_LD_LIBRARY_PATH(rpath)
111 def LOCAL_CACHE(ctx, name):
112 '''return a named build cache dictionary, used to store
113 state inside other functions'''
121 def LOCAL_CACHE_SET(ctx, cachename, key, value):
122 '''set a value in a local cache'''
123 cache = LOCAL_CACHE(ctx, cachename)
128 def ASSERT(ctx, expression, msg):
129 '''a build assert call'''
131 raise Errors.WafError("ERROR: %s\n" % msg)
132 Build.BuildContext.ASSERT = ASSERT
135 def SUBDIR(bld, subdir, list):
136 '''create a list of files by pre-pending each with a subdir name'''
138 for l in TO_LIST(list):
139 ret = ret + os.path.normpath(os.path.join(subdir, l)) + ' '
141 Build.BuildContext.SUBDIR = SUBDIR
144 def dict_concat(d1, d2):
145 '''concatenate two dictionaries d1 += d2'''
150 def ADD_COMMAND(opt, name, function):
151 '''add a new top level command to waf'''
152 Context.g_module.__dict__[name] = function
154 Options.OptionsContext.ADD_COMMAND = ADD_COMMAND
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)
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))
169 if getattr(y, 'more_includes', None):
170 self.includes += " " + y.more_includes
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("/")
182 # Work out how much of the filepath is shared by start and path.
183 i = len(os.path.commonprefix([start_list, path_list]))
185 rel_list = ['..'] * (len(start_list)-i) + path_list[i:]
188 return os.path.join(*rel_list)
191 def unique_list(seq):
192 '''return a uniquified list in the same order as the existing list'''
196 if item in seen: continue
202 def TO_LIST(str, delimiter=None):
203 '''Split a list, preserving quoted strings and existing lists'''
206 if isinstance(str, list):
207 # we need to return a new independent list...
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
217 return shlex.split(str)
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)
226 if re.match('\$\{\w+\}', v):
229 raise KeyError("Failed to find variable %s in %s in env %s <%s>" % (vname, string, env.__class__, str(env)))
231 if isinstance(v, list):
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
244 def recursive_dirlist(dir, relbase, pattern=None):
245 '''recursive directory list'''
247 for f in os.listdir(dir):
249 if os.path.isdir(f2):
250 ret.extend(recursive_dirlist(f2, relbase))
252 if pattern and not fnmatch.fnmatch(f, pattern):
254 ret.append(os_path_relpath(f2, relbase))
262 if dir.endswith("/"):
265 if os.path.isdir(dir):
267 mkdir_p(os.path.dirname(dir))
271 def SUBST_VARS_RECURSIVE(string, env):
272 '''recursively expand variables'''
276 while (string.find('${') != -1 and limit > 0):
277 string = subst_vars_error(string, env)
283 def EXPAND_VARIABLES(ctx, varstr, vars=None):
284 '''expand variables from a user supplied dictionary
286 This is most useful when you pass vars=locals() to expand
287 all your local variables in strings
290 if isinstance(varstr, list):
293 ret.append(EXPAND_VARIABLES(ctx, s, vars=vars))
296 if not isinstance(varstr, str):
299 env = ConfigSet.ConfigSet()
301 # substitute on user supplied dict if avaiilable
303 for v in vars.keys():
305 ret = SUBST_VARS_RECURSIVE(ret, env)
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)
316 Build.BuildContext.EXPAND_VARIABLES = EXPAND_VARIABLES
322 '''run a external command, return exit code or signal'''
324 cmd = SUBST_VARS_RECURSIVE(cmd, env)
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))
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')
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)
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)
351 print('Python test failed: %s' % cmd)
356 # make sure we have md5. some systems don't have it
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
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')
370 Context.SIG_NIL = hash('abcd')
371 class replace_md5(object):
374 def update(self, val):
375 self.val = hash((self.val, val))
379 return self.digest().encode('hex')
380 def replace_h_file(filename):
381 f = open(filename, 'rb')
384 filename = f.read(100000)
388 Utils.md5 = replace_md5
389 Task.md5 = replace_md5
390 Utils.h_file = replace_h_file
393 def LOAD_ENVIRONMENT():
394 '''load the configuration environment, allowing access to env vars
396 env = ConfigSet.ConfigSet()
398 p = os.path.join(Context.g_module.out, 'c4che/default'+CACHE_SUFFIX)
400 except (OSError, IOError):
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
411 Build.BuildContext.IS_NEWER = IS_NEWER
415 def RECURSE(ctx, directory):
416 '''recurse into a directory, relative to the curdir or top level'''
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)
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:
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))
439 Options.OptionsContext.RECURSE = RECURSE
440 Build.BuildContext.RECURSE = RECURSE
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:
448 makeflags = os.environ.get('MAKEFLAGS')
449 if makeflags is None:
453 # we need to use shlex.split to cope with the escaping of spaces
455 for opt in shlex.split(makeflags):
456 # options can come either as -x or as x
458 options.verbose = Logs.verbose = int(opt[2:])
460 Logs.zones = ['runner']
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"
472 setattr(options, opt[0:loc], opt[loc+1:])
475 if re.search(r'j[0-9]*$', v):
477 jobs = opt.strip('j')
480 elif re.search(r'-j[0-9]*$', opt):
482 jobs = opt.strip('-j')
488 elif jobs_set and jobs:
489 options.jobs = int(jobs)
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,
497 allow_unknown=allow_unknown)
498 CHECK_MAKEFLAGS(options)
499 if options.jobs == 1:
501 # waflib.Runner.Parallel processes jobs inline if the possible number
502 # of jobs is just 1. But (at least in waf <= 2.0.12) it still calls
503 # create a waflib.Runner.Spawner() which creates a single
504 # waflib.Runner.Consumer() thread that tries to process jobs from the
507 # This has strange effects, which are not noticed typically,
508 # but at least on AIX python has broken threading and fails
511 # So we just add a dummy Spawner class.
512 class NoOpSpawner(object):
513 def __init__(self, master):
515 from waflib import Runner
516 Runner.Spawner = NoOpSpawner
517 return options, commands, envvars
518 Options.OptionsContext.parse_cmd_args = wafsamba_options_parse_cmd_args
522 def option_group(opt, name):
523 '''find or create an option group'''
525 if name in option_groups:
526 return option_groups[name]
527 gr = opt.add_option_group(name)
528 option_groups[name] = gr
530 Options.OptionsContext.option_group = option_group
533 def save_file(filename, contents, create_dir=False):
534 '''save data to a file'''
536 mkdir_p(os.path.dirname(filename))
538 f = open(filename, 'w')
546 def load_file(filename):
547 '''return contents of a file'''
549 f = open(filename, 'r')
557 def reconfigure(ctx):
558 '''rerun configure if necessary'''
559 if not os.path.exists(".lock-wscript"):
560 raise Errors.WafError('configure has not been run')
561 import samba_wildcard
562 bld = samba_wildcard.fake_build_environment()
563 Configure.autoconfig = True
564 Scripting.check_configured(bld)
567 def map_shlib_extension(ctx, name, python=False):
568 '''map a filename with a shared library extension of .so to the real shlib name'''
571 if name[-1:].isdigit():
572 # some libraries have specified versions in the wscript rule
574 (root1, ext1) = os.path.splitext(name)
576 return ctx.env.pyext_PATTERN % root1
578 (root2, ext2) = os.path.splitext(ctx.env.cshlib_PATTERN)
580 Build.BuildContext.map_shlib_extension = map_shlib_extension
582 def apply_pattern(filename, pattern):
583 '''apply a filename pattern to a filename that may have a directory component'''
584 dirname = os.path.dirname(filename)
586 return pattern % filename
587 basename = os.path.basename(filename)
588 return os.path.join(dirname, pattern % basename)
590 def make_libname(ctx, name, nolibprefix=False, version=None, python=False):
591 """make a library filename
593 nolibprefix: don't include the lib prefix
594 version : add a version number
595 python : if we should use python module name conventions"""
598 libname = apply_pattern(name, ctx.env.pyext_PATTERN)
600 libname = apply_pattern(name, ctx.env.cshlib_PATTERN)
601 if nolibprefix and libname[0:3] == 'lib':
602 libname = libname[3:]
604 if version[0] == '.':
605 version = version[1:]
606 (root, ext) = os.path.splitext(libname)
608 # special case - version goes before the prefix
609 libname = "%s.%s%s" % (root, version, ext)
611 libname = "%s%s.%s" % (root, ext, version)
613 Build.BuildContext.make_libname = make_libname
616 def get_tgt_list(bld):
617 '''return a list of build objects for samba'''
619 targets = LOCAL_CACHE(bld, 'TARGET_TYPE')
621 # build a list of task generators we are interested in
625 if not type in ['SUBSYSTEM', 'MODULE', 'BINARY', 'LIBRARY', 'ASN1', 'PYTHON']:
627 t = bld.get_tgen_by_name(tgt)
629 Logs.error("Target %s of type %s has no task generator" % (tgt, type))
634 from waflib.Context import WSCRIPT_FILE
635 def PROCESS_SEPARATE_RULE(self, rule):
636 ''' cause waf to process additional script based on `rule'.
637 You should have file named wscript_<stage>_rule in the current directory
638 where stage is either 'configure' or 'build'
641 if isinstance(self, Configure.ConfigurationContext):
643 elif isinstance(self, Build.BuildContext):
645 file_path = os.path.join(self.path.abspath(), WSCRIPT_FILE+'_'+stage+'_'+rule)
646 node = self.root.find_node(file_path)
649 cache = self.recurse_cache
650 except AttributeError:
651 cache = self.recurse_cache = {}
652 if node not in cache:
654 self.pre_recurse(node)
656 function_code = node.read('rU', None)
657 exec(compile(function_code, node.abspath(), 'exec'), self.exec_dict)
659 self.post_recurse(node)
661 Build.BuildContext.PROCESS_SEPARATE_RULE = PROCESS_SEPARATE_RULE
662 ConfigurationContext.PROCESS_SEPARATE_RULE = PROCESS_SEPARATE_RULE
664 def AD_DC_BUILD_IS_ENABLED(self):
665 if self.CONFIG_SET('AD_DC_BUILD_IS_ENABLED'):
669 Build.BuildContext.AD_DC_BUILD_IS_ENABLED = AD_DC_BUILD_IS_ENABLED
671 @feature('cprogram', 'cshlib', 'cstaticlib')
672 @after('apply_lib_vars')
673 @before('apply_obj_vars')
674 def samba_before_apply_obj_vars(self):
675 """before apply_obj_vars for uselib, this removes the standard paths"""
677 def is_standard_libpath(env, path):
678 for _path in env.STANDARD_LIBPATH:
679 if _path == os.path.normpath(path):
686 if is_standard_libpath(v, i):
689 for i in v['LIBPATH']:
690 if is_standard_libpath(v, i):
691 v['LIBPATH'].remove(i)
693 def samba_add_onoff_option(opt, option, help=(), dest=None, default=True,
694 with_name="with", without_name="without"):
697 elif default is True:
699 elif default is False:
702 default_str = str(default)
705 help = ("Build with %s support (default=%s)" % (option, default_str))
707 dest = "with_%s" % option.replace('-', '_')
709 with_val = "--%s-%s" % (with_name, option)
710 without_val = "--%s-%s" % (without_name, option)
712 opt.add_option(with_val, help=help, action="store_true", dest=dest,
714 opt.add_option(without_val, help=SUPPRESS_HELP, action="store_false",
716 Options.OptionsContext.samba_add_onoff_option = samba_add_onoff_option