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 Build, os, sys, Options, Utils, Task, re, fnmatch, Logs
5 from TaskGen import feature, before
6 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 ######################################################
39 # this is used as a decorator to make functions only
40 # run once. Based on the idea from
41 # http://stackoverflow.com/questions/815110/is-there-a-decorator-to-simply-cache-function-return-values
42 def runonce(function):
44 def runonce_wrapper(*args):
45 if args in runonce_ret:
46 return runonce_ret[args]
49 runonce_ret[args] = ret
51 return runonce_wrapper
54 def ADD_LD_LIBRARY_PATH(path):
55 '''add something to LD_LIBRARY_PATH'''
56 if 'LD_LIBRARY_PATH' in os.environ:
57 oldpath = os.environ['LD_LIBRARY_PATH']
60 newpath = oldpath.split(':')
61 if not path in newpath:
63 os.environ['LD_LIBRARY_PATH'] = ':'.join(newpath)
66 def needs_private_lib(bld, target):
67 '''return True if a target links to a private library'''
68 for lib in getattr(target, "final_libs", []):
69 t = bld.name_to_obj(lib, bld.env)
70 if t and getattr(t, 'private_library', False):
75 def install_rpath(target):
76 '''the rpath value for installation'''
80 if bld.env.RPATH_ON_INSTALL:
81 ret.add(bld.EXPAND_VARIABLES(bld.env.LIBDIR))
82 if bld.env.RPATH_ON_INSTALL_PRIVATE and needs_private_lib(bld, target):
83 ret.add(bld.EXPAND_VARIABLES(bld.env.PRIVATELIBDIR))
88 '''the rpath value for build'''
89 rpaths = [os.path.normpath('%s/%s' % (bld.env.BUILD_DIRECTORY, d)) for d in ("shared", "shared/private")]
91 if bld.env.RPATH_ON_BUILD:
94 ADD_LD_LIBRARY_PATH(rpath)
99 def LOCAL_CACHE(ctx, name):
100 '''return a named build cache dictionary, used to store
101 state inside other functions'''
109 def LOCAL_CACHE_SET(ctx, cachename, key, value):
110 '''set a value in a local cache'''
111 cache = LOCAL_CACHE(ctx, cachename)
116 def ASSERT(ctx, expression, msg):
117 '''a build assert call'''
119 raise Utils.WafError("ERROR: %s\n" % msg)
120 Build.BuildContext.ASSERT = ASSERT
123 def SUBDIR(bld, subdir, list):
124 '''create a list of files by pre-pending each with a subdir name'''
126 for l in TO_LIST(list):
127 ret = ret + os.path.normpath(os.path.join(subdir, l)) + ' '
129 Build.BuildContext.SUBDIR = SUBDIR
132 def dict_concat(d1, d2):
133 '''concatenate two dictionaries d1 += d2'''
139 def exec_command(self, cmd, **kw):
140 '''this overrides the 'waf -v' debug output to be in a nice
141 unix like format instead of a python list.
142 Thanks to ita on #waf for this'''
145 if isinstance(cmd, list):
147 debug('runner: %s' % _cmd)
149 self.log.write('%s\n' % cmd)
152 if not kw.get('cwd', None):
154 except AttributeError:
155 self.cwd = kw['cwd'] = self.bldnode.abspath()
156 return Utils.exec_command(cmd, **kw)
157 Build.BuildContext.exec_command = exec_command
160 def ADD_COMMAND(opt, name, function):
161 '''add a new top level command to waf'''
162 Utils.g_module.__dict__[name] = function
164 Options.Handler.ADD_COMMAND = ADD_COMMAND
167 @feature('cc', 'cshlib', 'cprogram')
168 @before('apply_core','exec_rule')
169 def process_depends_on(self):
170 '''The new depends_on attribute for build rules
171 allow us to specify a dependency on output from
172 a source generation rule'''
173 if getattr(self , 'depends_on', None):
174 lst = self.to_list(self.depends_on)
176 y = self.bld.name_to_obj(x, self.env)
177 self.bld.ASSERT(y is not None, "Failed to find dependency %s of %s" % (x, self.name))
179 if getattr(y, 'more_includes', None):
180 self.includes += " " + y.more_includes
183 os_path_relpath = getattr(os.path, 'relpath', None)
184 if os_path_relpath is None:
185 # Python < 2.6 does not have os.path.relpath, provide a replacement
186 # (imported from Python2.6.5~rc2)
187 def os_path_relpath(path, start):
188 """Return a relative version of a path"""
189 start_list = os.path.abspath(start).split("/")
190 path_list = os.path.abspath(path).split("/")
192 # Work out how much of the filepath is shared by start and path.
193 i = len(os.path.commonprefix([start_list, path_list]))
195 rel_list = ['..'] * (len(start_list)-i) + path_list[i:]
198 return os.path.join(*rel_list)
201 def unique_list(seq):
202 '''return a uniquified list in the same order as the existing list'''
206 if item in seen: continue
212 def TO_LIST(str, delimiter=None):
213 '''Split a list, preserving quoted strings and existing lists'''
216 if isinstance(str, list):
217 # we need to return a new independent list...
221 lst = str.split(delimiter)
222 # the string may have had quotes in it, now we
223 # check if we did have quotes, and use the slower shlex
227 return shlex.split(str)
231 def subst_vars_error(string, env):
232 '''substitute vars, throw an error if a variable is not defined'''
233 lst = re.split('(\$\{\w+\})', string)
236 if re.match('\$\{\w+\}', v):
239 raise KeyError("Failed to find variable %s in %s" % (vname, string))
246 def SUBST_ENV_VAR(ctx, varname):
247 '''Substitute an environment variable for any embedded variables'''
248 return subst_vars_error(ctx.env[varname], ctx.env)
249 Build.BuildContext.SUBST_ENV_VAR = SUBST_ENV_VAR
252 def ENFORCE_GROUP_ORDERING(bld):
253 '''enforce group ordering for the project. This
254 makes the group ordering apply only when you specify
255 a target with --target'''
256 if Options.options.compile_targets:
258 @before('exec_rule', 'apply_core', 'collect')
259 def force_previous_groups(self):
260 if getattr(self.bld, 'enforced_group_ordering', False):
262 self.bld.enforced_group_ordering = True
265 tm = self.bld.task_manager
266 return [x for x in tm.groups_names if id(tm.groups_names[x]) == id(g)][0]
271 for g in bld.task_manager.groups:
272 for t in g.tasks_gen:
275 debug('group: Forcing up to group %s for target %s',
276 group_name(g), self.name or self.target)
283 for i in xrange(len(bld.task_manager.groups)):
284 g = bld.task_manager.groups[i]
285 bld.task_manager.current_group = i
288 debug('group: Forcing group %s', group_name(g))
289 for t in g.tasks_gen:
290 if not getattr(t, 'forced_groups', False):
291 debug('group: Posting %s', t.name or t.target)
292 t.forced_groups = True
294 Build.BuildContext.ENFORCE_GROUP_ORDERING = ENFORCE_GROUP_ORDERING
297 def recursive_dirlist(dir, relbase, pattern=None):
298 '''recursive directory list'''
300 for f in os.listdir(dir):
302 if os.path.isdir(f2):
303 ret.extend(recursive_dirlist(f2, relbase))
305 if pattern and not fnmatch.fnmatch(f, pattern):
307 ret.append(os_path_relpath(f2, relbase))
315 if dir.endswith("/"):
318 if os.path.isdir(dir):
320 mkdir_p(os.path.dirname(dir))
324 def SUBST_VARS_RECURSIVE(string, env):
325 '''recursively expand variables'''
329 while (string.find('${') != -1 and limit > 0):
330 string = subst_vars_error(string, env)
336 def EXPAND_VARIABLES(ctx, varstr, vars=None):
337 '''expand variables from a user supplied dictionary
339 This is most useful when you pass vars=locals() to expand
340 all your local variables in strings
343 if isinstance(varstr, list):
346 ret.append(EXPAND_VARIABLES(ctx, s, vars=vars))
349 if not isinstance(varstr, str):
353 env = Environment.Environment()
355 # substitute on user supplied dict if avaiilable
357 for v in vars.keys():
359 ret = SUBST_VARS_RECURSIVE(ret, env)
361 # if anything left, subst on the environment as well
362 if ret.find('${') != -1:
363 ret = SUBST_VARS_RECURSIVE(ret, ctx.env)
364 # make sure there is nothing left. Also check for the common
365 # typo of $( instead of ${
366 if ret.find('${') != -1 or ret.find('$(') != -1:
367 Logs.error('Failed to substitute all variables in varstr=%s' % ret)
370 Build.BuildContext.EXPAND_VARIABLES = EXPAND_VARIABLES
376 '''run a external command, return exit code or signal'''
378 cmd = SUBST_VARS_RECURSIVE(cmd, env)
380 status = os.system(cmd)
381 if os.WIFEXITED(status):
382 return os.WEXITSTATUS(status)
383 if os.WIFSIGNALED(status):
384 return - os.WTERMSIG(status)
385 Logs.error("Unknown exit reason %d for command: %s" (status, cmd))
389 # make sure we have md5. some systems don't have it
391 from hashlib import md5
392 # Even if hashlib.md5 exists, it may be unusable.
393 # Try to use MD5 function. In FIPS mode this will cause an exception
394 # and we'll get to the replacement code
399 # repeat the same check here, mere success of import is not enough.
400 # Try to use MD5 function. In FIPS mode this will cause an exception
401 foo = md5.md5('abcd')
404 Constants.SIG_NIL = hash('abcd')
405 class replace_md5(object):
408 def update(self, val):
409 self.val = hash((self.val, val))
413 return self.digest().encode('hex')
414 def replace_h_file(filename):
415 f = open(filename, 'rb')
418 filename = f.read(100000)
422 Utils.md5 = replace_md5
423 Task.md5 = replace_md5
424 Utils.h_file = replace_h_file
427 def LOAD_ENVIRONMENT():
428 '''load the configuration environment, allowing access to env vars
431 env = Environment.Environment()
433 env.load('.lock-wscript')
434 env.load(env.blddir + '/c4che/default.cache.py')
440 def IS_NEWER(bld, file1, file2):
441 '''return True if file1 is newer than file2'''
442 t1 = os.stat(os.path.join(bld.curdir, file1)).st_mtime
443 t2 = os.stat(os.path.join(bld.curdir, file2)).st_mtime
445 Build.BuildContext.IS_NEWER = IS_NEWER
449 def RECURSE(ctx, directory):
450 '''recurse into a directory, relative to the curdir or top level'''
452 visited_dirs = ctx.visited_dirs
454 visited_dirs = ctx.visited_dirs = set()
455 d = os.path.join(ctx.curdir, directory)
456 if os.path.exists(d):
457 abspath = os.path.abspath(d)
459 abspath = os.path.abspath(os.path.join(Utils.g_module.srcdir, directory))
460 ctxclass = ctx.__class__.__name__
461 key = ctxclass + ':' + abspath
462 if key in visited_dirs:
465 visited_dirs.add(key)
466 relpath = os_path_relpath(abspath, ctx.curdir)
467 if ctxclass == 'Handler':
468 return ctx.sub_options(relpath)
469 if ctxclass == 'ConfigurationContext':
470 return ctx.sub_config(relpath)
471 if ctxclass == 'BuildContext':
472 return ctx.add_subdirs(relpath)
473 Logs.error('Unknown RECURSE context class', ctxclass)
475 Options.Handler.RECURSE = RECURSE
476 Build.BuildContext.RECURSE = RECURSE
479 def CHECK_MAKEFLAGS(bld):
480 '''check for MAKEFLAGS environment variable in case we are being
481 called from a Makefile try to honor a few make command line flags'''
482 if not 'WAF_MAKE' in os.environ:
484 makeflags = os.environ.get('MAKEFLAGS')
485 if makeflags is None:
488 # we need to use shlex.split to cope with the escaping of spaces
490 for opt in shlex.split(makeflags):
491 # options can come either as -x or as x
493 Options.options.verbose = Logs.verbose = int(opt[2:])
495 Logs.zones = ['runner']
498 elif opt[0].isupper() and opt.find('=') != -1:
499 # this allows us to set waf options on the make command line
500 # for example, if you do "make FOO=blah", then we set the
501 # option 'FOO' in Options.options, to blah. If you look in wafsamba/wscript
502 # you will see that the command line accessible options have their dest=
503 # set to uppercase, to allow for passing of options from make in this way
504 # this is also how "make test TESTS=testpattern" works, and
505 # "make VERBOSE=1" as well as things like "make SYMBOLCHECK=1"
507 setattr(Options.options, opt[0:loc], opt[loc+1:])
513 Options.options.keep = True
517 Options.options.keep = True
520 Options.options.jobs = 1
522 Build.BuildContext.CHECK_MAKEFLAGS = CHECK_MAKEFLAGS
526 def option_group(opt, name):
527 '''find or create an option group'''
529 if name in option_groups:
530 return option_groups[name]
531 gr = opt.add_option_group(name)
532 option_groups[name] = gr
534 Options.Handler.option_group = option_group
537 def save_file(filename, contents, create_dir=False):
538 '''save data to a file'''
540 mkdir_p(os.path.dirname(filename))
542 f = open(filename, 'w')
550 def load_file(filename):
551 '''return contents of a file'''
553 f = open(filename, 'r')
561 def reconfigure(ctx):
562 '''rerun configure if necessary'''
563 import Configure, samba_wildcard, Scripting
564 if not os.path.exists(".lock-wscript"):
565 raise Utils.WafError('configure has not been run')
566 bld = samba_wildcard.fake_build_environment()
567 Configure.autoconfig = True
568 Scripting.check_configured(bld)
571 def map_shlib_extension(ctx, name, python=False):
572 '''map a filename with a shared library extension of .so to the real shlib name'''
575 if name[-1:].isdigit():
576 # some libraries have specified versions in the wscript rule
578 (root1, ext1) = os.path.splitext(name)
580 (root2, ext2) = os.path.splitext(ctx.env.pyext_PATTERN)
582 (root2, ext2) = os.path.splitext(ctx.env.shlib_PATTERN)
584 Build.BuildContext.map_shlib_extension = map_shlib_extension
586 def apply_pattern(filename, pattern):
587 '''apply a filename pattern to a filename that may have a directory component'''
588 dirname = os.path.dirname(filename)
590 return pattern % filename
591 basename = os.path.basename(filename)
592 return os.path.join(dirname, pattern % basename)
594 def make_libname(ctx, name, nolibprefix=False, version=None, python=False):
595 """make a library filename
597 nolibprefix: don't include the lib prefix
598 version : add a version number
599 python : if we should use python module name conventions"""
602 libname = apply_pattern(name, ctx.env.pyext_PATTERN)
604 libname = apply_pattern(name, ctx.env.shlib_PATTERN)
605 if nolibprefix and libname[0:3] == 'lib':
606 libname = libname[3:]
608 if version[0] == '.':
609 version = version[1:]
610 (root, ext) = os.path.splitext(libname)
612 # special case - version goes before the prefix
613 libname = "%s.%s%s" % (root, version, ext)
615 libname = "%s%s.%s" % (root, ext, version)
617 Build.BuildContext.make_libname = make_libname
620 def get_tgt_list(bld):
621 '''return a list of build objects for samba'''
623 targets = LOCAL_CACHE(bld, 'TARGET_TYPE')
625 # build a list of task generators we are interested in
629 if not type in ['SUBSYSTEM', 'MODULE', 'BINARY', 'LIBRARY', 'ASN1', 'PYTHON']:
631 t = bld.name_to_obj(tgt, bld.env)
633 Logs.error("Target %s of type %s has no task generator" % (tgt, type))
638 from Constants import WSCRIPT_FILE
639 def PROCESS_SEPARATE_RULE(self, rule):
640 ''' cause waf to process additional script based on `rule'.
641 You should have file named wscript_<stage>_rule in the current directory
642 where stage is either 'configure' or 'build'
644 ctxclass = self.__class__.__name__
646 if ctxclass == 'ConfigurationContext':
648 elif ctxclass == 'BuildContext':
650 file_path = os.path.join(self.curdir, WSCRIPT_FILE+'_'+stage+'_'+rule)
651 txt = load_file(file_path)
654 if getattr(self.__class__, 'pre_recurse', None):
655 dc = self.pre_recurse(txt, file_path, self.curdir)
656 exec(compile(txt, file_path, 'exec'), dc)
657 if getattr(self.__class__, 'post_recurse', None):
658 dc = self.post_recurse(txt, file_path, self.curdir)
660 Build.BuildContext.PROCESS_SEPARATE_RULE = PROCESS_SEPARATE_RULE
661 ConfigurationContext.PROCESS_SEPARATE_RULE = PROCESS_SEPARATE_RULE
663 def AD_DC_BUILD_IS_ENABLED(self):
664 if self.CONFIG_SET('AD_DC_BUILD_IS_ENABLED'):
668 Build.BuildContext.AD_DC_BUILD_IS_ENABLED = AD_DC_BUILD_IS_ENABLED