build:wafsamba: Remove samba_utils.runonce
[samba.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 import Build, Options, Utils, Task, Logs, Configure
6 from TaskGen import feature, before, after
7 from Configure import conf, ConfigurationContext
8 from Logs import debug
9
10 # TODO: make this a --option
11 LIB_PATH="shared"
12
13
14 # sigh, python octal constants are a mess
15 MODE_644 = int('644', 8)
16 MODE_755 = int('755', 8)
17
18 @conf
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]))
24         sys.exit(1)
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))
27     return True
28
29
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:
34         return None
35     return cache[target]
36
37
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']
42     else:
43         oldpath = ''
44     newpath = oldpath.split(':')
45     if not path in newpath:
46         newpath.append(path)
47         os.environ['LD_LIBRARY_PATH'] = ':'.join(newpath)
48
49
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):
55             return True
56     return False
57
58
59 def install_rpath(target):
60     '''the rpath value for installation'''
61     bld = target.bld
62     bld.env['RPATH'] = []
63     ret = set()
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))
68     return list(ret)
69
70
71 def build_rpath(bld):
72     '''the rpath value for build'''
73     rpaths = [os.path.normpath('%s/%s' % (bld.env.BUILD_DIRECTORY, d)) for d in ("shared", "shared/private")]
74     bld.env['RPATH'] = []
75     if bld.env.RPATH_ON_BUILD:
76         return rpaths
77     for rpath in rpaths:
78         ADD_LD_LIBRARY_PATH(rpath)
79     return []
80
81
82 @conf
83 def LOCAL_CACHE(ctx, name):
84     '''return a named build cache dictionary, used to store
85        state inside other functions'''
86     if name in ctx.env:
87         return ctx.env[name]
88     ctx.env[name] = {}
89     return ctx.env[name]
90
91
92 @conf
93 def LOCAL_CACHE_SET(ctx, cachename, key, value):
94     '''set a value in a local cache'''
95     cache = LOCAL_CACHE(ctx, cachename)
96     cache[key] = value
97
98
99 @conf
100 def ASSERT(ctx, expression, msg):
101     '''a build assert call'''
102     if not expression:
103         raise Utils.WafError("ERROR: %s\n" % msg)
104 Build.BuildContext.ASSERT = ASSERT
105
106
107 def SUBDIR(bld, subdir, list):
108     '''create a list of files by pre-pending each with a subdir name'''
109     ret = ''
110     for l in TO_LIST(list):
111         ret = ret + os.path.normpath(os.path.join(subdir, l)) + ' '
112     return ret
113 Build.BuildContext.SUBDIR = SUBDIR
114
115
116 def dict_concat(d1, d2):
117     '''concatenate two dictionaries d1 += d2'''
118     for t in d2:
119         if t not in d1:
120             d1[t] = d2[t]
121
122
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'''
127     _cmd = cmd
128     if isinstance(cmd, list):
129         _cmd = ' '.join(cmd)
130     debug('runner: %s' % _cmd)
131     if self.log:
132         self.log.write('%s\n' % cmd)
133         kw['log'] = self.log
134     try:
135         if not kw.get('cwd', None):
136             kw['cwd'] = self.cwd
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
141
142
143 def ADD_COMMAND(opt, name, function):
144     '''add a new top level command to waf'''
145     Utils.g_module.__dict__[name] = function
146     opt.name = function
147 Options.Handler.ADD_COMMAND = ADD_COMMAND
148
149
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)
158         for x in lst:
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))
161             y.post()
162             if getattr(y, 'more_includes', None):
163                   self.includes += " " + y.more_includes
164
165
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("/")
174
175         # Work out how much of the filepath is shared by start and path.
176         i = len(os.path.commonprefix([start_list, path_list]))
177
178         rel_list = ['..'] * (len(start_list)-i) + path_list[i:]
179         if not rel_list:
180             return start
181         return os.path.join(*rel_list)
182
183
184 def unique_list(seq):
185     '''return a uniquified list in the same order as the existing list'''
186     seen = {}
187     result = []
188     for item in seq:
189         if item in seen: continue
190         seen[item] = True
191         result.append(item)
192     return result
193
194
195 def TO_LIST(str, delimiter=None):
196     '''Split a list, preserving quoted strings and existing lists'''
197     if str is None:
198         return []
199     if isinstance(str, list):
200         # we need to return a new independent list...
201         return list(str)
202     if len(str) == 0:
203         return []
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
207     # if we need to
208     for e in lst:
209         if e[0] == '"':
210             return shlex.split(str)
211     return lst
212
213
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)
217     out = []
218     for v in lst:
219         if re.match('\$\{\w+\}', v):
220             vname = v[2:-1]
221             if not vname in env:
222                 raise KeyError("Failed to find variable %s in %s" % (vname, string))
223             v = env[vname]
224         out.append(v)
225     return ''.join(out)
226
227
228 @conf
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
233
234
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:
240         @feature('*')
241         @before('exec_rule', 'apply_core', 'collect')
242         def force_previous_groups(self):
243             if getattr(self.bld, 'enforced_group_ordering', False):
244                 return
245             self.bld.enforced_group_ordering = True
246
247             def group_name(g):
248                 tm = self.bld.task_manager
249                 return [x for x in tm.groups_names if id(tm.groups_names[x]) == id(g)][0]
250
251             my_id = id(self)
252             bld = self.bld
253             stop = None
254             for g in bld.task_manager.groups:
255                 for t in g.tasks_gen:
256                     if id(t) == my_id:
257                         stop = id(g)
258                         debug('group: Forcing up to group %s for target %s',
259                               group_name(g), self.name or self.target)
260                         break
261                 if stop is not None:
262                     break
263             if stop is None:
264                 return
265
266             for i in xrange(len(bld.task_manager.groups)):
267                 g = bld.task_manager.groups[i]
268                 bld.task_manager.current_group = i
269                 if id(g) == stop:
270                     break
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
276                         t.post()
277 Build.BuildContext.ENFORCE_GROUP_ORDERING = ENFORCE_GROUP_ORDERING
278
279
280 def recursive_dirlist(dir, relbase, pattern=None):
281     '''recursive directory list'''
282     ret = []
283     for f in os.listdir(dir):
284         f2 = dir + '/' + f
285         if os.path.isdir(f2):
286             ret.extend(recursive_dirlist(f2, relbase))
287         else:
288             if pattern and not fnmatch.fnmatch(f, pattern):
289                 continue
290             ret.append(os_path_relpath(f2, relbase))
291     return ret
292
293
294 def mkdir_p(dir):
295     '''like mkdir -p'''
296     if not dir:
297         return
298     if dir.endswith("/"):
299         mkdir_p(dir[:-1])
300         return
301     if os.path.isdir(dir):
302         return
303     mkdir_p(os.path.dirname(dir))
304     os.mkdir(dir)
305
306
307 def SUBST_VARS_RECURSIVE(string, env):
308     '''recursively expand variables'''
309     if string is None:
310         return string
311     limit=100
312     while (string.find('${') != -1 and limit > 0):
313         string = subst_vars_error(string, env)
314         limit -= 1
315     return string
316
317
318 @conf
319 def EXPAND_VARIABLES(ctx, varstr, vars=None):
320     '''expand variables from a user supplied dictionary
321
322     This is most useful when you pass vars=locals() to expand
323     all your local variables in strings
324     '''
325
326     if isinstance(varstr, list):
327         ret = []
328         for s in varstr:
329             ret.append(EXPAND_VARIABLES(ctx, s, vars=vars))
330         return ret
331
332     if not isinstance(varstr, str):
333         return varstr
334
335     import Environment
336     env = Environment.Environment()
337     ret = varstr
338     # substitute on user supplied dict if avaiilable
339     if vars is not None:
340         for v in vars.keys():
341             env[v] = vars[v]
342         ret = SUBST_VARS_RECURSIVE(ret, env)
343
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)
351         sys.exit(1)
352     return ret
353 Build.BuildContext.EXPAND_VARIABLES = EXPAND_VARIABLES
354
355
356 def RUN_COMMAND(cmd,
357                 env=None,
358                 shell=False):
359     '''run a external command, return exit code or signal'''
360     if env:
361         cmd = SUBST_VARS_RECURSIVE(cmd, env)
362
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))
369     return -1
370
371
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')
376     result = 0
377     for interp in env.python_interpreters:
378         for testfile in testfiles:
379             cmd = "PYTHONPATH=%s %s %s" % (pythonpath, interp, testfile)
380             if extra_env:
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)
385             if ret:
386                 print('Python test failed: %s' % cmd)
387                 result = ret
388     return result
389
390
391 # make sure we have md5. some systems don't have it
392 try:
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
397     foo = md5('abcd')
398 except:
399     try:
400         import md5
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')
404     except:
405         import Constants
406         Constants.SIG_NIL = hash('abcd')
407         class replace_md5(object):
408             def __init__(self):
409                 self.val = None
410             def update(self, val):
411                 self.val = hash((self.val, val))
412             def digest(self):
413                 return str(self.val)
414             def hexdigest(self):
415                 return self.digest().encode('hex')
416         def replace_h_file(filename):
417             f = open(filename, 'rb')
418             m = replace_md5()
419             while (filename):
420                 filename = f.read(100000)
421                 m.update(filename)
422             f.close()
423             return m.digest()
424         Utils.md5 = replace_md5
425         Task.md5 = replace_md5
426         Utils.h_file = replace_h_file
427
428
429 def LOAD_ENVIRONMENT():
430     '''load the configuration environment, allowing access to env vars
431        from new commands'''
432     import Environment
433     env = Environment.Environment()
434     try:
435         env.load('.lock-wscript')
436         env.load(env.blddir + '/c4che/default.cache.py')
437     except:
438         pass
439     return env
440
441
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
446     return t1 > t2
447 Build.BuildContext.IS_NEWER = IS_NEWER
448
449
450 @conf
451 def RECURSE(ctx, directory):
452     '''recurse into a directory, relative to the curdir or top level'''
453     try:
454         visited_dirs = ctx.visited_dirs
455     except:
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)
460     else:
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:
465         # already done it
466         return
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)
476     raise
477 Options.Handler.RECURSE = RECURSE
478 Build.BuildContext.RECURSE = RECURSE
479
480
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:
485         return
486     makeflags = os.environ.get('MAKEFLAGS')
487     if makeflags is None:
488         return
489     jobs_set = False
490     # we need to use shlex.split to cope with the escaping of spaces
491     # in makeflags
492     for opt in shlex.split(makeflags):
493         # options can come either as -x or as x
494         if opt[0:2] == 'V=':
495             Options.options.verbose = Logs.verbose = int(opt[2:])
496             if Logs.verbose > 0:
497                 Logs.zones = ['runner']
498             if Logs.verbose > 2:
499                 Logs.zones = ['*']
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"
508             loc = opt.find('=')
509             setattr(Options.options, opt[0:loc], opt[loc+1:])
510         elif opt[0] != '-':
511             for v in opt:
512                 if v == 'j':
513                     jobs_set = True
514                 elif v == 'k':
515                     Options.options.keep = True
516         elif opt == '-j':
517             jobs_set = True
518         elif opt == '-k':
519             Options.options.keep = True
520     if not jobs_set:
521         # default to one job
522         Options.options.jobs = 1
523
524 Build.BuildContext.CHECK_MAKEFLAGS = CHECK_MAKEFLAGS
525
526 option_groups = {}
527
528 def option_group(opt, name):
529     '''find or create an option group'''
530     global option_groups
531     if name in option_groups:
532         return option_groups[name]
533     gr = opt.add_option_group(name)
534     option_groups[name] = gr
535     return gr
536 Options.Handler.option_group = option_group
537
538
539 def save_file(filename, contents, create_dir=False):
540     '''save data to a file'''
541     if create_dir:
542         mkdir_p(os.path.dirname(filename))
543     try:
544         f = open(filename, 'w')
545         f.write(contents)
546         f.close()
547     except:
548         return False
549     return True
550
551
552 def load_file(filename):
553     '''return contents of a file'''
554     try:
555         f = open(filename, 'r')
556         r = f.read()
557         f.close()
558     except:
559         return None
560     return r
561
562
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)
571
572
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'''
575     if name is None:
576         return None
577     if name[-1:].isdigit():
578         # some libraries have specified versions in the wscript rule
579         return name
580     (root1, ext1) = os.path.splitext(name)
581     if python:
582         return ctx.env.pyext_PATTERN % root1
583     else:
584         (root2, ext2) = os.path.splitext(ctx.env.shlib_PATTERN)
585     return root1+ext2
586 Build.BuildContext.map_shlib_extension = map_shlib_extension
587
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)
591     if not dirname:
592         return pattern % filename
593     basename = os.path.basename(filename)
594     return os.path.join(dirname, pattern % basename)
595
596 def make_libname(ctx, name, nolibprefix=False, version=None, python=False):
597     """make a library filename
598          Options:
599               nolibprefix: don't include the lib prefix
600               version    : add a version number
601               python     : if we should use python module name conventions"""
602
603     if python:
604         libname = apply_pattern(name, ctx.env.pyext_PATTERN)
605     else:
606         libname = apply_pattern(name, ctx.env.shlib_PATTERN)
607     if nolibprefix and libname[0:3] == 'lib':
608         libname = libname[3:]
609     if version:
610         if version[0] == '.':
611             version = version[1:]
612         (root, ext) = os.path.splitext(libname)
613         if ext == ".dylib":
614             # special case - version goes before the prefix
615             libname = "%s.%s%s" % (root, version, ext)
616         else:
617             libname = "%s%s.%s" % (root, ext, version)
618     return libname
619 Build.BuildContext.make_libname = make_libname
620
621
622 def get_tgt_list(bld):
623     '''return a list of build objects for samba'''
624
625     targets = LOCAL_CACHE(bld, 'TARGET_TYPE')
626
627     # build a list of task generators we are interested in
628     tgt_list = []
629     for tgt in targets:
630         type = targets[tgt]
631         if not type in ['SUBSYSTEM', 'MODULE', 'BINARY', 'LIBRARY', 'ASN1', 'PYTHON']:
632             continue
633         t = bld.get_tgen_by_name(tgt)
634         if t is None:
635             Logs.error("Target %s of type %s has no task generator" % (tgt, type))
636             sys.exit(1)
637         tgt_list.append(t)
638     return tgt_list
639
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'
645     '''
646     stage = ''
647     if isinstance(self, Configure.ConfigurationContext):
648         stage = 'configure'
649     elif isinstance(self, Build.BuildContext):
650         stage = 'build'
651     file_path = os.path.join(self.curdir, WSCRIPT_FILE+'_'+stage+'_'+rule)
652     txt = load_file(file_path)
653     if txt:
654         dc = {'ctx': self}
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)
660
661 Build.BuildContext.PROCESS_SEPARATE_RULE = PROCESS_SEPARATE_RULE
662 ConfigurationContext.PROCESS_SEPARATE_RULE = PROCESS_SEPARATE_RULE
663
664 def AD_DC_BUILD_IS_ENABLED(self):
665     if self.CONFIG_SET('AD_DC_BUILD_IS_ENABLED'):
666         return True
667     return False
668
669 Build.BuildContext.AD_DC_BUILD_IS_ENABLED = AD_DC_BUILD_IS_ENABLED
670
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"""
676
677     def is_standard_libpath(env, path):
678         for _path in env.STANDARD_LIBPATH:
679             if _path == os.path.normpath(path):
680                 return True
681         return False
682
683     v = self.env
684
685     for i in v['RPATH']:
686         if is_standard_libpath(v, i):
687             v['RPATH'].remove(i)
688
689     for i in v['LIBPATH']:
690         if is_standard_libpath(v, i):
691             v['LIBPATH'].remove(i)
692