build: support systems without rpath
[amitay/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 Build, os, sys, Options, Utils
5 from TaskGen import feature, before
6 from Configure import conf
7 from Logs import debug
8 import shlex
9
10 # TODO: make this a --option
11 LIB_PATH="shared"
12
13
14 ##########################################################
15 # create a node with a new name, based on an existing node
16 def NEW_NODE(node, name):
17     ret = node.parent.find_or_declare([name])
18     ASSERT(node, ret is not None, "Unable to find new target with name '%s' from '%s'" % (
19             name, node.name))
20     return ret
21
22
23 #############################################################
24 # set a value in a local cache
25 # return False if it's already set
26 def SET_TARGET_TYPE(ctx, target, value):
27     cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
28     if target in cache:
29         ASSERT(ctx, cache[target] == value,
30                "Target '%s' re-defined as %s - was %s" % (target, value, cache[target]))
31         debug("task_gen: Skipping duplicate target %s (curdir=%s)" % (target, ctx.curdir))
32         return False
33     LOCAL_CACHE_SET(ctx, 'TARGET_TYPE', target, value)
34     debug("task_gen: Target '%s' created of type '%s' in %s" % (target, value, ctx.curdir))
35     return True
36
37
38 def GET_TARGET_TYPE(ctx, target):
39     '''get target type from cache'''
40     cache = LOCAL_CACHE(ctx, 'TARGET_TYPE')
41     if not target in cache:
42         return None
43     return cache[target]
44
45
46 ######################################################
47 # this is used as a decorator to make functions only
48 # run once. Based on the idea from
49 # http://stackoverflow.com/questions/815110/is-there-a-decorator-to-simply-cache-function-return-values
50 runonce_ret = {}
51 def runonce(function):
52     def wrapper(*args):
53         if args in runonce_ret:
54             return runonce_ret[args]
55         else:
56             ret = function(*args)
57             runonce_ret[args] = ret
58             return ret
59     return wrapper
60
61
62
63 def set_rpath(bld):
64     '''setup the default rpath'''
65     if bld.env.RPATH_ON_BUILD:
66         rpath = os.path.normpath('%s/%s' % (bld.env['BUILD_DIRECTORY'], LIB_PATH))
67         bld.env.append_value('RPATH', '-Wl,-rpath=%s' % rpath)
68     else:
69         os.environ['LD_LIBRARY_PATH'] = os.path.normpath('%s/../shared' % bld.srcnode.abspath(bld.env))
70 Build.BuildContext.set_rpath = set_rpath
71
72 def install_rpath(bld):
73     '''the rpath value for installation'''
74     if bld.env.RPATH_ON_INSTALL:
75         return ['-Wl,-rpath=%s/lib' % bld.env.PREFIX]
76     return []
77
78
79 #############################################################
80 # return a named build cache dictionary, used to store
81 # state inside the following functions
82 @conf
83 def LOCAL_CACHE(ctx, name):
84     if name in ctx.env:
85         return ctx.env[name]
86     ctx.env[name] = {}
87     return ctx.env[name]
88
89
90 #############################################################
91 # set a value in a local cache
92 @conf
93 def LOCAL_CACHE_SET(ctx, cachename, key, value):
94     cache = LOCAL_CACHE(ctx, cachename)
95     cache[key] = value
96
97 #############################################################
98 # a build assert call
99 @conf
100 def ASSERT(ctx, expression, msg):
101     if not expression:
102         sys.stderr.write("ERROR: %s\n" % msg)
103         raise AssertionError
104 Build.BuildContext.ASSERT = ASSERT
105
106 ################################################################
107 # create a list of files by pre-pending each with a subdir name
108 def SUBDIR(bld, subdir, list):
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 # d1 += d2
117 def dict_concat(d1, d2):
118     for t in d2:
119         if t not in d1:
120             d1[t] = d2[t]
121
122 ############################################################
123 # this overrides the 'waf -v' debug output to be in a nice
124 # unix like format instead of a python list.
125 # Thanks to ita on #waf for this
126 def exec_command(self, cmd, **kw):
127     import Utils, Logs
128     _cmd = cmd
129     if isinstance(cmd, list):
130         _cmd = ' '.join(cmd)
131     debug('runner: %s' % _cmd)
132     if self.log:
133         self.log.write('%s\n' % cmd)
134         kw['log'] = self.log
135     try:
136         if not kw.get('cwd', None):
137             kw['cwd'] = self.cwd
138     except AttributeError:
139         self.cwd = kw['cwd'] = self.bldnode.abspath()
140     return Utils.exec_command(cmd, **kw)
141 Build.BuildContext.exec_command = exec_command
142
143
144 ##########################################################
145 # add a new top level command to waf
146 def ADD_COMMAND(opt, name, function):
147     Utils.g_module.__dict__[name] = function
148     opt.name = function
149 Options.Handler.ADD_COMMAND = ADD_COMMAND
150
151
152 @feature('cc', 'cshlib', 'cprogram')
153 @before('apply_core','exec_rule')
154 def process_depends_on(self):
155     '''The new depends_on attribute for build rules
156        allow us to specify a dependency on output from
157        a source generation rule'''
158     if getattr(self , 'depends_on', None):
159         lst = self.to_list(self.depends_on)
160         for x in lst:
161             y = self.bld.name_to_obj(x, self.env)
162             self.bld.ASSERT(y is not None, "Failed to find dependency %s of %s" % (x, self.name))
163             y.post()
164             if getattr(y, 'more_includes', None):
165                   self.includes += " " + y.more_includes
166
167
168 #@feature('cprogram', 'cc', 'cshlib')
169 #@before('apply_core')
170 #def process_generated_dependencies(self):
171 #    '''Ensure that any dependent source generation happens
172 #       before any task that requires the output'''
173 #    if getattr(self , 'depends_on', None):
174 #        lst = self.to_list(self.depends_on)
175 #        for x in lst:
176 #            y = self.bld.name_to_obj(x, self.env)
177 #            y.post()
178
179
180 #import TaskGen, Task
181 #
182 #old_post_run = Task.Task.post_run
183 #def new_post_run(self):
184 #    self.cached = True
185 #    return old_post_run(self)
186 #
187 #for y in ['cc', 'cxx']:
188 #    TaskGen.classes[y].post_run = new_post_run
189
190 def ENABLE_MAGIC_ORDERING(bld):
191     '''enable automatic build order constraint calculation
192        see page 35 of the waf book'''
193     print "NOT Enabling magic ordering"
194     #bld.use_the_magic()
195 Build.BuildContext.ENABLE_MAGIC_ORDERING = ENABLE_MAGIC_ORDERING
196
197
198 os_path_relpath = getattr(os.path, 'relpath', None)
199 if os_path_relpath is None:
200     # Python < 2.6 does not have os.path.relpath, provide a replacement
201     # (imported from Python2.6.5~rc2)
202     def os_path_relpath(path, start):
203         """Return a relative version of a path"""
204         start_list = os.path.abspath(start).split("/")
205         path_list = os.path.abspath(path).split("/")
206
207         # Work out how much of the filepath is shared by start and path.
208         i = len(os.path.commonprefix([start_list, path_list]))
209
210         rel_list = ['..'] * (len(start_list)-i) + path_list[i:]
211         if not rel_list:
212             return start
213         return os.path.join(*rel_list)
214
215
216 # this is a useful way of debugging some of the rules in waf
217 from TaskGen import feature, after
218 @feature('dbg')
219 @after('apply_core', 'apply_obj_vars_cc')
220 def dbg(self):
221         if self.target == 'HEIMDAL_HEIM_ASN1':
222                 print "@@@@@@@@@@@@@@2", self.includes, self.env._CCINCFLAGS
223
224 def unique_list(seq):
225     '''return a uniquified list in the same order as the existing list'''
226     seen = {}
227     result = []
228     for item in seq:
229         if item in seen: continue
230         seen[item] = True
231         result.append(item)
232     return result
233
234 def TO_LIST(str):
235     '''Split a list, preserving quoted strings and existing lists'''
236     if isinstance(str, list):
237         return str
238     lst = str.split()
239     # the string may have had quotes in it, now we
240     # check if we did have quotes, and use the slower shlex
241     # if we need to
242     for e in lst:
243         if e[0] == '"':
244             return shlex.split(str)
245     return lst
246
247 @conf
248 def SUBST_ENV_VAR(ctx, varname):
249     '''Substitute an environment variable for any embedded variables'''
250     return Utils.subst_vars(ctx.env[varname], ctx.env)
251 Build.BuildContext.SUBST_ENV_VAR = SUBST_ENV_VAR
252
253
254 def ENFORCE_GROUP_ORDERING(bld):
255     '''enforce group ordering for the project. This
256        makes the group ordering apply only when you specify
257        a target with --target'''
258     if Options.options.compile_targets:
259         @feature('*')
260         def force_previous_groups(self):
261             my_id = id(self)
262
263             bld = self.bld
264             stop = None
265             for g in bld.task_manager.groups:
266                 for t in g.tasks_gen:
267                     if id(t) == my_id:
268                         stop = id(g)
269                         break
270                 if stop is None:
271                     return
272
273                 for g in bld.task_manager.groups:
274                     if id(g) == stop:
275                         break
276                     for t in g.tasks_gen:
277                         t.post()
278 Build.BuildContext.ENFORCE_GROUP_ORDERING = ENFORCE_GROUP_ORDERING
279
280 # @feature('cc')
281 # @before('apply_lib_vars')
282 # def process_objects(self):
283 #     if getattr(self, 'add_objects', None):
284 #         lst = self.to_list(self.add_objects)
285 #         for x in lst:
286 #             y = self.name_to_obj(x)
287 #             if not y:
288 #                 raise Utils.WafError('object %r was not found in uselib_local (required by add_objects %r)' % (x, self.name))
289 #             y.post()
290 #             self.env.append_unique('INC_PATHS', y.env.INC_PATHS)
291
292
293 def recursive_dirlist(dir, relbase):
294     '''recursive directory list'''
295     ret = []
296     for f in os.listdir(dir):
297         f2 = dir + '/' + f
298         if os.path.isdir(f2):
299             ret.extend(recursive_dirlist(f2, relbase))
300         else:
301             ret.append(os_path_relpath(f2, relbase))
302     return ret
303
304
305 def mkdir_p(dir):
306     '''like mkdir -p'''
307     if os.path.isdir(dir):
308         return
309     mkdir_p(os.path.dirname(dir))
310     os.mkdir(dir)
311
312
313 def SUBST_VARS_RECURSIVE(string, env):
314     '''recursively expand variables'''
315     if string is None:
316         return string
317     limit=100
318     while (string.find('${') != -1 and limit > 0):
319         string = Utils.subst_vars(string, env)
320         limit -= 1
321     return string
322
323
324 def RUN_COMMAND(cmd,
325                 env=None,
326                 shell=False):
327     '''run a external command, return exit code or signal'''
328     if env:
329         cmd = SUBST_VARS_RECURSIVE(cmd, env)
330
331     status = os.system(cmd)
332     if os.WIFEXITED(status):
333         return os.WEXITSTATUS(status)
334     if os.WIFSIGNALED(status):
335         return - os.WTERMSIG(status)
336     print "Unknown exit reason %d for command: %s" (status, cmd)
337     return -1