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