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_744 = int('744', 8)
21 MODE_755 = int('755', 8)
22 MODE_777 = int('777', 8)
25 # override in order to propagate the argument "mandatory"
29 mandatory = kw['mandatory']
34 except Errors.ConfigurationError:
38 fun.__name__ = f.__name__
39 if 'mandatory' in inspect.getsource(f):
42 setattr(Configure.ConfigurationContext, f.__name__, fun)
43 setattr(Build.BuildContext, f.__name__, fun)
46 Configure.conftest = conf
49 def SET_TARGET_TYPE(ctx, target, value):
50 '''set the target type of a target'''
51 cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
52 if target in cache and cache[target] != 'EMPTY':
53 Logs.error("ERROR: Target '%s' in directory %s re-defined as %s - was %s" % (target, ctx.path.abspath(), value, cache[target]))
55 LOCAL_CACHE_SET(ctx, 'TARGET_TYPE', target, value)
56 debug("task_gen: Target '%s' created of type '%s' in %s" % (target, value, ctx.path.abspath()))
60 def GET_TARGET_TYPE(ctx, target):
61 '''get target type from cache'''
62 cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
63 if not target in cache:
68 def ADD_LD_LIBRARY_PATH(path):
69 '''add something to LD_LIBRARY_PATH'''
70 if 'LD_LIBRARY_PATH' in os.environ:
71 oldpath = os.environ['LD_LIBRARY_PATH']
74 newpath = oldpath.split(':')
75 if not path in newpath:
77 os.environ['LD_LIBRARY_PATH'] = ':'.join(newpath)
80 def needs_private_lib(bld, target):
81 '''return True if a target links to a private library'''
82 for lib in getattr(target, "final_libs", []):
83 t = bld.get_tgen_by_name(lib)
84 if t and getattr(t, 'private_library', False):
89 def install_rpath(target):
90 '''the rpath value for installation'''
94 if bld.env.RPATH_ON_INSTALL:
95 ret.add(bld.EXPAND_VARIABLES(bld.env.LIBDIR))
96 if bld.env.RPATH_ON_INSTALL_PRIVATE and needs_private_lib(bld, target):
97 ret.add(bld.EXPAND_VARIABLES(bld.env.PRIVATELIBDIR))
101 def build_rpath(bld):
102 '''the rpath value for build'''
103 rpaths = [os.path.normpath('%s/%s' % (bld.env.BUILD_DIRECTORY, d)) for d in ("shared", "shared/private")]
104 bld.env['RPATH'] = []
105 if bld.env.RPATH_ON_BUILD:
108 ADD_LD_LIBRARY_PATH(rpath)
113 def LOCAL_CACHE(ctx, name):
114 '''return a named build cache dictionary, used to store
115 state inside other functions'''
123 def LOCAL_CACHE_SET(ctx, cachename, key, value):
124 '''set a value in a local cache'''
125 cache = LOCAL_CACHE(ctx, cachename)
130 def ASSERT(ctx, expression, msg):
131 '''a build assert call'''
133 raise Errors.WafError("ERROR: %s\n" % msg)
134 Build.BuildContext.ASSERT = ASSERT
137 def SUBDIR(bld, subdir, list):
138 '''create a list of files by pre-pending each with a subdir name'''
140 for l in TO_LIST(list):
141 ret = ret + os.path.normpath(os.path.join(subdir, l)) + ' '
143 Build.BuildContext.SUBDIR = SUBDIR
146 def dict_concat(d1, d2):
147 '''concatenate two dictionaries d1 += d2'''
152 def ADD_COMMAND(opt, name, function):
153 '''add a new top level command to waf'''
154 Context.g_module.__dict__[name] = function
156 Options.OptionsContext.ADD_COMMAND = ADD_COMMAND
159 @feature('c', 'cc', 'cshlib', 'cprogram')
160 @before('apply_core','exec_rule')
161 def process_depends_on(self):
162 '''The new depends_on attribute for build rules
163 allow us to specify a dependency on output from
164 a source generation rule'''
165 if getattr(self , 'depends_on', None):
166 lst = self.to_list(self.depends_on)
168 y = self.bld.get_tgen_by_name(x)
169 self.bld.ASSERT(y is not None, "Failed to find dependency %s of %s" % (x, self.name))
171 if getattr(y, 'more_includes', None):
172 self.includes += " " + y.more_includes
175 os_path_relpath = getattr(os.path, 'relpath', None)
176 if os_path_relpath is None:
177 # Python < 2.6 does not have os.path.relpath, provide a replacement
178 # (imported from Python2.6.5~rc2)
179 def os_path_relpath(path, start):
180 """Return a relative version of a path"""
181 start_list = os.path.abspath(start).split("/")
182 path_list = os.path.abspath(path).split("/")
184 # Work out how much of the filepath is shared by start and path.
185 i = len(os.path.commonprefix([start_list, path_list]))
187 rel_list = ['..'] * (len(start_list)-i) + path_list[i:]
190 return os.path.join(*rel_list)
193 def unique_list(seq):
194 '''return a uniquified list in the same order as the existing list'''
198 if item in seen: continue
204 def TO_LIST(str, delimiter=None):
205 '''Split a list, preserving quoted strings and existing lists'''
208 if isinstance(str, list):
209 # we need to return a new independent list...
213 lst = str.split(delimiter)
214 # the string may have had quotes in it, now we
215 # check if we did have quotes, and use the slower shlex
219 return shlex.split(str)
223 def subst_vars_error(string, env):
224 '''substitute vars, throw an error if a variable is not defined'''
225 lst = re.split('(\$\{\w+\})', string)
228 if re.match('\$\{\w+\}', v):
231 raise KeyError("Failed to find variable %s in %s in env %s <%s>" % (vname, string, env.__class__, str(env)))
233 if isinstance(v, list):
240 def SUBST_ENV_VAR(ctx, varname):
241 '''Substitute an environment variable for any embedded variables'''
242 return subst_vars_error(ctx.env[varname], ctx.env)
243 Build.BuildContext.SUBST_ENV_VAR = SUBST_ENV_VAR
246 def recursive_dirlist(dir, relbase, pattern=None):
247 '''recursive directory list'''
249 for f in os.listdir(dir):
251 if os.path.isdir(f2):
252 ret.extend(recursive_dirlist(f2, relbase))
254 if pattern and not fnmatch.fnmatch(f, pattern):
256 ret.append(os_path_relpath(f2, relbase))
264 if dir.endswith("/"):
267 if os.path.isdir(dir):
269 mkdir_p(os.path.dirname(dir))
273 def SUBST_VARS_RECURSIVE(string, env):
274 '''recursively expand variables'''
278 while (string.find('${') != -1 and limit > 0):
279 string = subst_vars_error(string, env)
285 def EXPAND_VARIABLES(ctx, varstr, vars=None):
286 '''expand variables from a user supplied dictionary
288 This is most useful when you pass vars=locals() to expand
289 all your local variables in strings
292 if isinstance(varstr, list):
295 ret.append(EXPAND_VARIABLES(ctx, s, vars=vars))
298 if not isinstance(varstr, str):
301 env = ConfigSet.ConfigSet()
303 # substitute on user supplied dict if avaiilable
305 for v in vars.keys():
307 ret = SUBST_VARS_RECURSIVE(ret, env)
309 # if anything left, subst on the environment as well
310 if ret.find('${') != -1:
311 ret = SUBST_VARS_RECURSIVE(ret, ctx.env)
312 # make sure there is nothing left. Also check for the common
313 # typo of $( instead of ${
314 if ret.find('${') != -1 or ret.find('$(') != -1:
315 Logs.error('Failed to substitute all variables in varstr=%s' % ret)
318 Build.BuildContext.EXPAND_VARIABLES = EXPAND_VARIABLES
324 '''run a external command, return exit code or signal'''
326 cmd = SUBST_VARS_RECURSIVE(cmd, env)
328 status = os.system(cmd)
329 if os.WIFEXITED(status):
330 return os.WEXITSTATUS(status)
331 if os.WIFSIGNALED(status):
332 return - os.WTERMSIG(status)
333 Logs.error("Unknown exit reason %d for command: %s" % (status, cmd))
337 def RUN_PYTHON_TESTS(testfiles, pythonpath=None, extra_env=None):
338 env = LOAD_ENVIRONMENT()
339 if pythonpath is None:
340 pythonpath = os.path.join(Context.g_module.out, 'python')
342 for interp in env.python_interpreters:
343 if not isinstance(interp, str):
344 interp = ' '.join(interp)
345 for testfile in testfiles:
346 cmd = "PYTHONPATH=%s %s %s" % (pythonpath, interp, testfile)
348 for key, value in extra_env.items():
349 cmd = "%s=%s %s" % (key, value, cmd)
350 print('Running Python test with %s: %s' % (interp, testfile))
351 ret = RUN_COMMAND(cmd)
353 print('Python test failed: %s' % cmd)
358 # make sure we have md5. some systems don't have it
360 from hashlib import md5
361 # Even if hashlib.md5 exists, it may be unusable.
362 # Try to use MD5 function. In FIPS mode this will cause an exception
363 # and we'll get to the replacement code
368 # repeat the same check here, mere success of import is not enough.
369 # Try to use MD5 function. In FIPS mode this will cause an exception
370 foo = md5.md5(b'abcd')
372 Context.SIG_NIL = hash('abcd')
373 class replace_md5(object):
376 def update(self, val):
377 self.val = hash((self.val, val))
381 return self.digest().encode('hex')
382 def replace_h_file(filename):
383 f = open(filename, 'rb')
386 filename = f.read(100000)
390 Utils.md5 = replace_md5
391 Task.md5 = replace_md5
392 Utils.h_file = replace_h_file
395 def LOAD_ENVIRONMENT():
396 '''load the configuration environment, allowing access to env vars
398 env = ConfigSet.ConfigSet()
400 p = os.path.join(Context.g_module.out, 'c4che/default'+CACHE_SUFFIX)
402 except (OSError, IOError):
407 def IS_NEWER(bld, file1, file2):
408 '''return True if file1 is newer than file2'''
409 curdir = bld.path.abspath()
410 t1 = os.stat(os.path.join(curdir, file1)).st_mtime
411 t2 = os.stat(os.path.join(curdir, file2)).st_mtime
413 Build.BuildContext.IS_NEWER = IS_NEWER
417 def RECURSE(ctx, directory):
418 '''recurse into a directory, relative to the curdir or top level'''
420 visited_dirs = ctx.visited_dirs
421 except AttributeError:
422 visited_dirs = ctx.visited_dirs = set()
423 d = os.path.join(ctx.path.abspath(), directory)
424 if os.path.exists(d):
425 abspath = os.path.abspath(d)
427 abspath = os.path.abspath(os.path.join(Context.g_module.top, directory))
428 ctxclass = ctx.__class__.__name__
429 key = ctxclass + ':' + abspath
430 if key in visited_dirs:
433 visited_dirs.add(key)
434 relpath = os_path_relpath(abspath, ctx.path.abspath())
435 if ctxclass in ['tmp', 'OptionsContext', 'ConfigurationContext', 'BuildContext']:
436 return ctx.recurse(relpath)
437 if 'waflib.extras.compat15' in sys.modules:
438 return ctx.recurse(relpath)
439 Logs.error('Unknown RECURSE context class: {}'.format(ctxclass))
441 Options.OptionsContext.RECURSE = RECURSE
442 Build.BuildContext.RECURSE = RECURSE
445 def CHECK_MAKEFLAGS(options):
446 '''check for MAKEFLAGS environment variable in case we are being
447 called from a Makefile try to honor a few make command line flags'''
448 if not 'WAF_MAKE' in os.environ:
450 makeflags = os.environ.get('MAKEFLAGS')
451 if makeflags is None:
455 # we need to use shlex.split to cope with the escaping of spaces
457 for opt in shlex.split(makeflags):
458 # options can come either as -x or as x
460 options.verbose = Logs.verbose = int(opt[2:])
462 Logs.zones = ['runner']
465 elif opt[0].isupper() and opt.find('=') != -1:
466 # this allows us to set waf options on the make command line
467 # for example, if you do "make FOO=blah", then we set the
468 # option 'FOO' in Options.options, to blah. If you look in wafsamba/wscript
469 # you will see that the command line accessible options have their dest=
470 # set to uppercase, to allow for passing of options from make in this way
471 # this is also how "make test TESTS=testpattern" works, and
472 # "make VERBOSE=1" as well as things like "make SYMBOLCHECK=1"
474 setattr(options, opt[0:loc], opt[loc+1:])
477 if re.search(r'j[0-9]*$', v):
479 jobs = opt.strip('j')
482 elif re.search(r'-j[0-9]*$', opt):
484 jobs = opt.strip('-j')
490 elif jobs_set and jobs:
491 options.jobs = int(jobs)
493 waflib_options_parse_cmd_args = Options.OptionsContext.parse_cmd_args
494 def wafsamba_options_parse_cmd_args(self, _args=None, cwd=None, allow_unknown=False):
495 (options, commands, envvars) = \
496 waflib_options_parse_cmd_args(self,
499 allow_unknown=allow_unknown)
500 CHECK_MAKEFLAGS(options)
501 if options.jobs == 1:
503 # waflib.Runner.Parallel processes jobs inline if the possible number
504 # of jobs is just 1. But (at least in waf <= 2.0.12) it still calls
505 # create a waflib.Runner.Spawner() which creates a single
506 # waflib.Runner.Consumer() thread that tries to process jobs from the
509 # This has strange effects, which are not noticed typically,
510 # but at least on AIX python has broken threading and fails
513 # So we just add a dummy Spawner class.
514 class NoOpSpawner(object):
515 def __init__(self, master):
517 from waflib import Runner
518 Runner.Spawner = NoOpSpawner
519 return options, commands, envvars
520 Options.OptionsContext.parse_cmd_args = wafsamba_options_parse_cmd_args
524 def option_group(opt, name):
525 '''find or create an option group'''
527 if name in option_groups:
528 return option_groups[name]
529 gr = opt.add_option_group(name)
530 option_groups[name] = gr
532 Options.OptionsContext.option_group = option_group
535 def save_file(filename, contents, create_dir=False):
536 '''save data to a file'''
538 mkdir_p(os.path.dirname(filename))
540 f = open(filename, 'w')
548 def load_file(filename):
549 '''return contents of a file'''
551 f = open(filename, 'r')
559 def reconfigure(ctx):
560 '''rerun configure if necessary'''
561 if not os.path.exists(".lock-wscript"):
562 raise Errors.WafError('configure has not been run')
563 import samba_wildcard
564 bld = samba_wildcard.fake_build_environment()
565 Configure.autoconfig = True
566 Scripting.check_configured(bld)
569 def map_shlib_extension(ctx, name, python=False):
570 '''map a filename with a shared library extension of .so to the real shlib name'''
573 if name[-1:].isdigit():
574 # some libraries have specified versions in the wscript rule
576 (root1, ext1) = os.path.splitext(name)
578 return ctx.env.pyext_PATTERN % root1
580 (root2, ext2) = os.path.splitext(ctx.env.cshlib_PATTERN)
582 Build.BuildContext.map_shlib_extension = map_shlib_extension
584 def apply_pattern(filename, pattern):
585 '''apply a filename pattern to a filename that may have a directory component'''
586 dirname = os.path.dirname(filename)
588 return pattern % filename
589 basename = os.path.basename(filename)
590 return os.path.join(dirname, pattern % basename)
592 def make_libname(ctx, name, nolibprefix=False, version=None, python=False):
593 """make a library filename
595 nolibprefix: don't include the lib prefix
596 version : add a version number
597 python : if we should use python module name conventions"""
600 libname = apply_pattern(name, ctx.env.pyext_PATTERN)
602 libname = apply_pattern(name, ctx.env.cshlib_PATTERN)
603 if nolibprefix and libname[0:3] == 'lib':
604 libname = libname[3:]
606 if version[0] == '.':
607 version = version[1:]
608 (root, ext) = os.path.splitext(libname)
610 # special case - version goes before the prefix
611 libname = "%s.%s%s" % (root, version, ext)
613 libname = "%s%s.%s" % (root, ext, version)
615 Build.BuildContext.make_libname = make_libname
618 def get_tgt_list(bld):
619 '''return a list of build objects for samba'''
621 targets = LOCAL_CACHE(bld, 'TARGET_TYPE')
623 # build a list of task generators we are interested in
627 if not type in ['SUBSYSTEM', 'MODULE', 'BINARY', 'LIBRARY', 'ASN1', 'PYTHON']:
629 t = bld.get_tgen_by_name(tgt)
631 Logs.error("Target %s of type %s has no task generator" % (tgt, type))
636 from waflib.Context import WSCRIPT_FILE
637 def PROCESS_SEPARATE_RULE(self, rule):
638 ''' cause waf to process additional script based on `rule'.
639 You should have file named wscript_<stage>_rule in the current directory
640 where stage is either 'configure' or 'build'
643 if isinstance(self, Configure.ConfigurationContext):
645 elif isinstance(self, Build.BuildContext):
647 file_path = os.path.join(self.path.abspath(), WSCRIPT_FILE+'_'+stage+'_'+rule)
648 node = self.root.find_node(file_path)
651 cache = self.recurse_cache
652 except AttributeError:
653 cache = self.recurse_cache = {}
654 if node not in cache:
656 self.pre_recurse(node)
658 function_code = node.read('rU', None)
659 exec(compile(function_code, node.abspath(), 'exec'), self.exec_dict)
661 self.post_recurse(node)
663 Build.BuildContext.PROCESS_SEPARATE_RULE = PROCESS_SEPARATE_RULE
664 ConfigurationContext.PROCESS_SEPARATE_RULE = PROCESS_SEPARATE_RULE
666 def AD_DC_BUILD_IS_ENABLED(self):
667 if self.CONFIG_SET('AD_DC_BUILD_IS_ENABLED'):
671 Build.BuildContext.AD_DC_BUILD_IS_ENABLED = AD_DC_BUILD_IS_ENABLED
673 @feature('cprogram', 'cshlib', 'cstaticlib')
674 @after('apply_lib_vars')
675 @before('apply_obj_vars')
676 def samba_before_apply_obj_vars(self):
677 """before apply_obj_vars for uselib, this removes the standard paths"""
679 def is_standard_libpath(env, path):
680 for _path in env.STANDARD_LIBPATH:
681 if _path == os.path.normpath(path):
688 if is_standard_libpath(v, i):
691 for i in v['LIBPATH']:
692 if is_standard_libpath(v, i):
693 v['LIBPATH'].remove(i)
695 def samba_add_onoff_option(opt, option, help=(), dest=None, default=True,
696 with_name="with", without_name="without"):
699 elif default is True:
701 elif default is False:
704 default_str = str(default)
707 help = ("Build with %s support (default=%s)" % (option, default_str))
709 dest = "with_%s" % option.replace('-', '_')
711 with_val = "--%s-%s" % (with_name, option)
712 without_val = "--%s-%s" % (without_name, option)
714 opt.add_option(with_val, help=help, action="store_true", dest=dest,
716 opt.add_option(without_val, help=SUPPRESS_HELP, action="store_false",
718 Options.OptionsContext.samba_add_onoff_option = samba_add_onoff_option