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
5 import Build, Options, Utils, Task, Logs, Configure
6 from TaskGen import feature, before, after
7 from Configure import conf, ConfigurationContext
10 # TODO: make this a --option
14 # sigh, python octal constants are a mess
15 MODE_644 = int('644', 8)
16 MODE_755 = int('755', 8)
19 def SET_TARGET_TYPE(ctx, target, value):
20 '''set the target type of a target'''
21 cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
22 if target in cache and cache[target] != 'EMPTY':
23 Logs.error("ERROR: Target '%s' in directory %s re-defined as %s - was %s" % (target, ctx.curdir, value, cache[target]))
25 LOCAL_CACHE_SET(ctx, 'TARGET_TYPE', target, value)
26 debug("task_gen: Target '%s' created of type '%s' in %s" % (target, value, ctx.curdir))
30 def GET_TARGET_TYPE(ctx, target):
31 '''get target type from cache'''
32 cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
33 if not target in cache:
38 def ADD_LD_LIBRARY_PATH(path):
39 '''add something to LD_LIBRARY_PATH'''
40 if 'LD_LIBRARY_PATH' in os.environ:
41 oldpath = os.environ['LD_LIBRARY_PATH']
44 newpath = oldpath.split(':')
45 if not path in newpath:
47 os.environ['LD_LIBRARY_PATH'] = ':'.join(newpath)
50 def needs_private_lib(bld, target):
51 '''return True if a target links to a private library'''
52 for lib in getattr(target, "final_libs", []):
53 t = bld.get_tgen_by_name(lib)
54 if t and getattr(t, 'private_library', False):
59 def install_rpath(target):
60 '''the rpath value for installation'''
64 if bld.env.RPATH_ON_INSTALL:
65 ret.add(bld.EXPAND_VARIABLES(bld.env.LIBDIR))
66 if bld.env.RPATH_ON_INSTALL_PRIVATE and needs_private_lib(bld, target):
67 ret.add(bld.EXPAND_VARIABLES(bld.env.PRIVATELIBDIR))
72 '''the rpath value for build'''
73 rpaths = [os.path.normpath('%s/%s' % (bld.env.BUILD_DIRECTORY, d)) for d in ("shared", "shared/private")]
75 if bld.env.RPATH_ON_BUILD:
78 ADD_LD_LIBRARY_PATH(rpath)
83 def LOCAL_CACHE(ctx, name):
84 '''return a named build cache dictionary, used to store
85 state inside other functions'''
93 def LOCAL_CACHE_SET(ctx, cachename, key, value):
94 '''set a value in a local cache'''
95 cache = LOCAL_CACHE(ctx, cachename)
100 def ASSERT(ctx, expression, msg):
101 '''a build assert call'''
103 raise Utils.WafError("ERROR: %s\n" % msg)
104 Build.BuildContext.ASSERT = ASSERT
107 def SUBDIR(bld, subdir, list):
108 '''create a list of files by pre-pending each with a subdir name'''
110 for l in TO_LIST(list):
111 ret = ret + os.path.normpath(os.path.join(subdir, l)) + ' '
113 Build.BuildContext.SUBDIR = SUBDIR
116 def dict_concat(d1, d2):
117 '''concatenate two dictionaries d1 += d2'''
123 def exec_command(self, cmd, **kw):
124 '''this overrides the 'waf -v' debug output to be in a nice
125 unix like format instead of a python list.
126 Thanks to ita on #waf for this'''
128 if isinstance(cmd, list):
130 debug('runner: %s' % _cmd)
132 self.log.write('%s\n' % cmd)
135 if not kw.get('cwd', None):
137 except AttributeError:
138 self.cwd = kw['cwd'] = self.bldnode.abspath()
139 return Utils.exec_command(cmd, **kw)
140 Build.BuildContext.exec_command = exec_command
143 def ADD_COMMAND(opt, name, function):
144 '''add a new top level command to waf'''
145 Utils.g_module.__dict__[name] = function
147 Options.Handler.ADD_COMMAND = ADD_COMMAND
150 @feature('c', 'cc', 'cshlib', 'cprogram')
151 @before('apply_core','exec_rule')
152 def process_depends_on(self):
153 '''The new depends_on attribute for build rules
154 allow us to specify a dependency on output from
155 a source generation rule'''
156 if getattr(self , 'depends_on', None):
157 lst = self.to_list(self.depends_on)
159 y = self.bld.get_tgen_by_name(x)
160 self.bld.ASSERT(y is not None, "Failed to find dependency %s of %s" % (x, self.name))
162 if getattr(y, 'more_includes', None):
163 self.includes += " " + y.more_includes
166 os_path_relpath = getattr(os.path, 'relpath', None)
167 if os_path_relpath is None:
168 # Python < 2.6 does not have os.path.relpath, provide a replacement
169 # (imported from Python2.6.5~rc2)
170 def os_path_relpath(path, start):
171 """Return a relative version of a path"""
172 start_list = os.path.abspath(start).split("/")
173 path_list = os.path.abspath(path).split("/")
175 # Work out how much of the filepath is shared by start and path.
176 i = len(os.path.commonprefix([start_list, path_list]))
178 rel_list = ['..'] * (len(start_list)-i) + path_list[i:]
181 return os.path.join(*rel_list)
184 def unique_list(seq):
185 '''return a uniquified list in the same order as the existing list'''
189 if item in seen: continue
195 def TO_LIST(str, delimiter=None):
196 '''Split a list, preserving quoted strings and existing lists'''
199 if isinstance(str, list):
200 # we need to return a new independent list...
204 lst = str.split(delimiter)
205 # the string may have had quotes in it, now we
206 # check if we did have quotes, and use the slower shlex
210 return shlex.split(str)
214 def subst_vars_error(string, env):
215 '''substitute vars, throw an error if a variable is not defined'''
216 lst = re.split('(\$\{\w+\})', string)
219 if re.match('\$\{\w+\}', v):
222 raise KeyError("Failed to find variable %s in %s" % (vname, string))
229 def SUBST_ENV_VAR(ctx, varname):
230 '''Substitute an environment variable for any embedded variables'''
231 return subst_vars_error(ctx.env[varname], ctx.env)
232 Build.BuildContext.SUBST_ENV_VAR = SUBST_ENV_VAR
235 def ENFORCE_GROUP_ORDERING(bld):
236 '''enforce group ordering for the project. This
237 makes the group ordering apply only when you specify
238 a target with --target'''
239 if Options.options.compile_targets:
241 @before('exec_rule', 'apply_core', 'collect')
242 def force_previous_groups(self):
243 if getattr(self.bld, 'enforced_group_ordering', False):
245 self.bld.enforced_group_ordering = True
248 tm = self.bld.task_manager
249 return [x for x in tm.groups_names if id(tm.groups_names[x]) == id(g)][0]
254 for g in bld.task_manager.groups:
255 for t in g.tasks_gen:
258 debug('group: Forcing up to group %s for target %s',
259 group_name(g), self.name or self.target)
266 for i in xrange(len(bld.task_manager.groups)):
267 g = bld.task_manager.groups[i]
268 bld.task_manager.current_group = i
271 debug('group: Forcing group %s', group_name(g))
272 for t in g.tasks_gen:
273 if not getattr(t, 'forced_groups', False):
274 debug('group: Posting %s', t.name or t.target)
275 t.forced_groups = True
277 Build.BuildContext.ENFORCE_GROUP_ORDERING = ENFORCE_GROUP_ORDERING
280 def recursive_dirlist(dir, relbase, pattern=None):
281 '''recursive directory list'''
283 for f in os.listdir(dir):
285 if os.path.isdir(f2):
286 ret.extend(recursive_dirlist(f2, relbase))
288 if pattern and not fnmatch.fnmatch(f, pattern):
290 ret.append(os_path_relpath(f2, relbase))
298 if dir.endswith("/"):
301 if os.path.isdir(dir):
303 mkdir_p(os.path.dirname(dir))
307 def SUBST_VARS_RECURSIVE(string, env):
308 '''recursively expand variables'''
312 while (string.find('${') != -1 and limit > 0):
313 string = subst_vars_error(string, env)
319 def EXPAND_VARIABLES(ctx, varstr, vars=None):
320 '''expand variables from a user supplied dictionary
322 This is most useful when you pass vars=locals() to expand
323 all your local variables in strings
326 if isinstance(varstr, list):
329 ret.append(EXPAND_VARIABLES(ctx, s, vars=vars))
332 if not isinstance(varstr, str):
336 env = Environment.Environment()
338 # substitute on user supplied dict if avaiilable
340 for v in vars.keys():
342 ret = SUBST_VARS_RECURSIVE(ret, env)
344 # if anything left, subst on the environment as well
345 if ret.find('${') != -1:
346 ret = SUBST_VARS_RECURSIVE(ret, ctx.env)
347 # make sure there is nothing left. Also check for the common
348 # typo of $( instead of ${
349 if ret.find('${') != -1 or ret.find('$(') != -1:
350 Logs.error('Failed to substitute all variables in varstr=%s' % ret)
353 Build.BuildContext.EXPAND_VARIABLES = EXPAND_VARIABLES
359 '''run a external command, return exit code or signal'''
361 cmd = SUBST_VARS_RECURSIVE(cmd, env)
363 status = os.system(cmd)
364 if os.WIFEXITED(status):
365 return os.WEXITSTATUS(status)
366 if os.WIFSIGNALED(status):
367 return - os.WTERMSIG(status)
368 Logs.error("Unknown exit reason %d for command: %s" (status, cmd))
372 def RUN_PYTHON_TESTS(testfiles, pythonpath=None, extra_env=None):
373 env = LOAD_ENVIRONMENT()
374 if pythonpath is None:
375 pythonpath = os.path.join(Utils.g_module.blddir, 'python')
377 for interp in env.python_interpreters:
378 for testfile in testfiles:
379 cmd = "PYTHONPATH=%s %s %s" % (pythonpath, interp, testfile)
381 for key, value in extra_env.items():
382 cmd = "%s=%s %s" % (key, value, cmd)
383 print('Running Python test with %s: %s' % (interp, testfile))
384 ret = RUN_COMMAND(cmd)
386 print('Python test failed: %s' % cmd)
391 # make sure we have md5. some systems don't have it
393 from hashlib import md5
394 # Even if hashlib.md5 exists, it may be unusable.
395 # Try to use MD5 function. In FIPS mode this will cause an exception
396 # and we'll get to the replacement code
401 # repeat the same check here, mere success of import is not enough.
402 # Try to use MD5 function. In FIPS mode this will cause an exception
403 foo = md5.md5('abcd')
406 Constants.SIG_NIL = hash('abcd')
407 class replace_md5(object):
410 def update(self, val):
411 self.val = hash((self.val, val))
415 return self.digest().encode('hex')
416 def replace_h_file(filename):
417 f = open(filename, 'rb')
420 filename = f.read(100000)
424 Utils.md5 = replace_md5
425 Task.md5 = replace_md5
426 Utils.h_file = replace_h_file
429 def LOAD_ENVIRONMENT():
430 '''load the configuration environment, allowing access to env vars
433 env = Environment.Environment()
435 env.load('.lock-wscript')
436 env.load(env.blddir + '/c4che/default.cache.py')
442 def IS_NEWER(bld, file1, file2):
443 '''return True if file1 is newer than file2'''
444 t1 = os.stat(os.path.join(bld.curdir, file1)).st_mtime
445 t2 = os.stat(os.path.join(bld.curdir, file2)).st_mtime
447 Build.BuildContext.IS_NEWER = IS_NEWER
451 def RECURSE(ctx, directory):
452 '''recurse into a directory, relative to the curdir or top level'''
454 visited_dirs = ctx.visited_dirs
456 visited_dirs = ctx.visited_dirs = set()
457 d = os.path.join(ctx.curdir, directory)
458 if os.path.exists(d):
459 abspath = os.path.abspath(d)
461 abspath = os.path.abspath(os.path.join(Utils.g_module.srcdir, directory))
462 ctxclass = ctx.__class__.__name__
463 key = ctxclass + ':' + abspath
464 if key in visited_dirs:
467 visited_dirs.add(key)
468 relpath = os_path_relpath(abspath, ctx.curdir)
469 if ctxclass == 'Handler':
470 return ctx.sub_options(relpath)
471 if ctxclass == 'ConfigurationContext':
472 return ctx.sub_config(relpath)
473 if ctxclass == 'BuildContext':
474 return ctx.add_subdirs(relpath)
475 Logs.error('Unknown RECURSE context class', ctxclass)
477 Options.Handler.RECURSE = RECURSE
478 Build.BuildContext.RECURSE = RECURSE
481 def CHECK_MAKEFLAGS(bld):
482 '''check for MAKEFLAGS environment variable in case we are being
483 called from a Makefile try to honor a few make command line flags'''
484 if not 'WAF_MAKE' in os.environ:
486 makeflags = os.environ.get('MAKEFLAGS')
487 if makeflags is None:
490 # we need to use shlex.split to cope with the escaping of spaces
492 for opt in shlex.split(makeflags):
493 # options can come either as -x or as x
495 Options.options.verbose = Logs.verbose = int(opt[2:])
497 Logs.zones = ['runner']
500 elif opt[0].isupper() and opt.find('=') != -1:
501 # this allows us to set waf options on the make command line
502 # for example, if you do "make FOO=blah", then we set the
503 # option 'FOO' in Options.options, to blah. If you look in wafsamba/wscript
504 # you will see that the command line accessible options have their dest=
505 # set to uppercase, to allow for passing of options from make in this way
506 # this is also how "make test TESTS=testpattern" works, and
507 # "make VERBOSE=1" as well as things like "make SYMBOLCHECK=1"
509 setattr(Options.options, opt[0:loc], opt[loc+1:])
515 Options.options.keep = True
519 Options.options.keep = True
522 Options.options.jobs = 1
524 Build.BuildContext.CHECK_MAKEFLAGS = CHECK_MAKEFLAGS
528 def option_group(opt, name):
529 '''find or create an option group'''
531 if name in option_groups:
532 return option_groups[name]
533 gr = opt.add_option_group(name)
534 option_groups[name] = gr
536 Options.Handler.option_group = option_group
539 def save_file(filename, contents, create_dir=False):
540 '''save data to a file'''
542 mkdir_p(os.path.dirname(filename))
544 f = open(filename, 'w')
552 def load_file(filename):
553 '''return contents of a file'''
555 f = open(filename, 'r')
563 def reconfigure(ctx):
564 '''rerun configure if necessary'''
565 import Configure, samba_wildcard, Scripting
566 if not os.path.exists(".lock-wscript"):
567 raise Utils.WafError('configure has not been run')
568 bld = samba_wildcard.fake_build_environment()
569 Configure.autoconfig = True
570 Scripting.check_configured(bld)
573 def map_shlib_extension(ctx, name, python=False):
574 '''map a filename with a shared library extension of .so to the real shlib name'''
577 if name[-1:].isdigit():
578 # some libraries have specified versions in the wscript rule
580 (root1, ext1) = os.path.splitext(name)
582 return ctx.env.pyext_PATTERN % root1
584 (root2, ext2) = os.path.splitext(ctx.env.shlib_PATTERN)
586 Build.BuildContext.map_shlib_extension = map_shlib_extension
588 def apply_pattern(filename, pattern):
589 '''apply a filename pattern to a filename that may have a directory component'''
590 dirname = os.path.dirname(filename)
592 return pattern % filename
593 basename = os.path.basename(filename)
594 return os.path.join(dirname, pattern % basename)
596 def make_libname(ctx, name, nolibprefix=False, version=None, python=False):
597 """make a library filename
599 nolibprefix: don't include the lib prefix
600 version : add a version number
601 python : if we should use python module name conventions"""
604 libname = apply_pattern(name, ctx.env.pyext_PATTERN)
606 libname = apply_pattern(name, ctx.env.shlib_PATTERN)
607 if nolibprefix and libname[0:3] == 'lib':
608 libname = libname[3:]
610 if version[0] == '.':
611 version = version[1:]
612 (root, ext) = os.path.splitext(libname)
614 # special case - version goes before the prefix
615 libname = "%s.%s%s" % (root, version, ext)
617 libname = "%s%s.%s" % (root, ext, version)
619 Build.BuildContext.make_libname = make_libname
622 def get_tgt_list(bld):
623 '''return a list of build objects for samba'''
625 targets = LOCAL_CACHE(bld, 'TARGET_TYPE')
627 # build a list of task generators we are interested in
631 if not type in ['SUBSYSTEM', 'MODULE', 'BINARY', 'LIBRARY', 'ASN1', 'PYTHON']:
633 t = bld.get_tgen_by_name(tgt)
635 Logs.error("Target %s of type %s has no task generator" % (tgt, type))
640 from Constants import WSCRIPT_FILE
641 def PROCESS_SEPARATE_RULE(self, rule):
642 ''' cause waf to process additional script based on `rule'.
643 You should have file named wscript_<stage>_rule in the current directory
644 where stage is either 'configure' or 'build'
647 if isinstance(self, Configure.ConfigurationContext):
649 elif isinstance(self, Build.BuildContext):
651 file_path = os.path.join(self.curdir, WSCRIPT_FILE+'_'+stage+'_'+rule)
652 txt = load_file(file_path)
655 if getattr(self.__class__, 'pre_recurse', None):
656 dc = self.pre_recurse(txt, file_path, self.curdir)
657 exec(compile(txt, file_path, 'exec'), dc)
658 if getattr(self.__class__, 'post_recurse', None):
659 dc = self.post_recurse(txt, file_path, self.curdir)
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)