blob: e66f49696239d357d095b2cfc78c2481b8c3c3e8 [file] [log] [blame]
José Fonseca97e2c5a2009-12-31 17:58:56 +00001"""custom
2
3Custom builders and methods.
4
5"""
6
7#
José Fonseca87712852014-01-17 16:27:50 +00008# Copyright 2008 VMware, Inc.
José Fonseca97e2c5a2009-12-31 17:58:56 +00009# All Rights Reserved.
10#
11# Permission is hereby granted, free of charge, to any person obtaining a
12# copy of this software and associated documentation files (the
13# "Software"), to deal in the Software without restriction, including
14# without limitation the rights to use, copy, modify, merge, publish,
15# distribute, sub license, and/or sell copies of the Software, and to
16# permit persons to whom the Software is furnished to do so, subject to
17# the following conditions:
18#
19# The above copyright notice and this permission notice (including the
20# next paragraph) shall be included in all copies or substantial portions
21# of the Software.
22#
23# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
José Fonseca87712852014-01-17 16:27:50 +000026# IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
José Fonseca97e2c5a2009-12-31 17:58:56 +000027# ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
28# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
29# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30#
31
32
José Fonseca97e2c5a2009-12-31 17:58:56 +000033import os.path
José Fonseca235225e2011-06-30 17:36:37 +010034import sys
35import subprocess
Jose Fonsecac521f2d2016-05-06 14:03:05 +010036import modulefinder
José Fonseca97e2c5a2009-12-31 17:58:56 +000037
38import SCons.Action
39import SCons.Builder
40import SCons.Scanner
41
42import fixes
43
Chia-I Wu582b5d82011-08-18 17:12:29 +080044import source_list
José Fonseca97e2c5a2009-12-31 17:58:56 +000045
Giuseppe Bilotta1b62b472016-05-25 07:32:08 -060046# the get_implicit_deps() method changed between 2.4 and 2.5: now it expects
47# a callable that takes a scanner as argument and returns a path, rather than
48# a path directly. We want to support both, so we need to detect the SCons version,
49# for which no API is provided by SCons 8-P
50
51scons_version = tuple(map(int, SCons.__version__.split('.')))
52
José Fonseca97e2c5a2009-12-31 17:58:56 +000053def quietCommandLines(env):
54 # Quiet command lines
55 # See also http://www.scons.org/wiki/HidingCommandLinesInOutput
56 env['ASCOMSTR'] = " Assembling $SOURCE ..."
57 env['ASPPCOMSTR'] = " Assembling $SOURCE ..."
58 env['CCCOMSTR'] = " Compiling $SOURCE ..."
59 env['SHCCCOMSTR'] = " Compiling $SOURCE ..."
60 env['CXXCOMSTR'] = " Compiling $SOURCE ..."
61 env['SHCXXCOMSTR'] = " Compiling $SOURCE ..."
62 env['ARCOMSTR'] = " Archiving $TARGET ..."
63 env['RANLIBCOMSTR'] = " Indexing $TARGET ..."
64 env['LINKCOMSTR'] = " Linking $TARGET ..."
65 env['SHLINKCOMSTR'] = " Linking $TARGET ..."
66 env['LDMODULECOMSTR'] = " Linking $TARGET ..."
67 env['SWIGCOMSTR'] = " Generating $TARGET ..."
José Fonseca54d8c5e2011-03-03 15:42:58 +000068 env['LEXCOMSTR'] = " Generating $TARGET ..."
69 env['YACCCOMSTR'] = " Generating $TARGET ..."
José Fonseca2311e2a2010-02-09 23:16:26 +000070 env['CODEGENCOMSTR'] = " Generating $TARGET ..."
José Fonseca37058c32011-05-04 14:10:24 +010071 env['INSTALLSTR'] = " Installing $TARGET ..."
José Fonseca97e2c5a2009-12-31 17:58:56 +000072
73
74def createConvenienceLibBuilder(env):
75 """This is a utility function that creates the ConvenienceLibrary
76 Builder in an Environment if it is not there already.
77
78 If it is already there, we return the existing one.
79
80 Based on the stock StaticLibrary and SharedLibrary builders.
81 """
82
83 try:
84 convenience_lib = env['BUILDERS']['ConvenienceLibrary']
85 except KeyError:
86 action_list = [ SCons.Action.Action("$ARCOM", "$ARCOMSTR") ]
87 if env.Detect('ranlib'):
88 ranlib_action = SCons.Action.Action("$RANLIBCOM", "$RANLIBCOMSTR")
89 action_list.append(ranlib_action)
90
91 convenience_lib = SCons.Builder.Builder(action = action_list,
92 emitter = '$LIBEMITTER',
93 prefix = '$LIBPREFIX',
94 suffix = '$LIBSUFFIX',
95 src_suffix = '$SHOBJSUFFIX',
96 src_builder = 'SharedObject')
97 env['BUILDERS']['ConvenienceLibrary'] = convenience_lib
98
99 return convenience_lib
100
101
José Fonseca97e2c5a2009-12-31 17:58:56 +0000102def python_scan(node, env, path):
103 # http://www.scons.org/doc/0.98.5/HTML/scons-user/c2781.html#AEN2789
Jose Fonsecac521f2d2016-05-06 14:03:05 +0100104 # https://docs.python.org/2/library/modulefinder.html
José Fonseca97e2c5a2009-12-31 17:58:56 +0000105 contents = node.get_contents()
106 source_dir = node.get_dir()
Jose Fonsecac521f2d2016-05-06 14:03:05 +0100107 finder = modulefinder.ModuleFinder()
108 finder.run_script(node.abspath)
José Fonseca97e2c5a2009-12-31 17:58:56 +0000109 results = []
Jose Fonsecac521f2d2016-05-06 14:03:05 +0100110 for name, mod in finder.modules.iteritems():
111 if mod.__file__ is None:
112 continue
113 assert os.path.exists(mod.__file__)
114 results.append(env.File(mod.__file__))
José Fonseca97e2c5a2009-12-31 17:58:56 +0000115 return results
116
117python_scanner = SCons.Scanner.Scanner(function = python_scan, skeys = ['.py'])
118
119
120def code_generate(env, script, target, source, command):
121 """Method to simplify code generation via python scripts.
122
123 http://www.scons.org/wiki/UsingCodeGenerators
124 http://www.scons.org/doc/0.98.5/HTML/scons-user/c2768.html
125 """
126
127 # We're generating code using Python scripts, so we have to be
128 # careful with our scons elements. This entry represents
129 # the generator file *in the source directory*.
130 script_src = env.File(script).srcnode()
131
132 # This command creates generated code *in the build directory*.
133 command = command.replace('$SCRIPT', script_src.path)
José Fonseca2311e2a2010-02-09 23:16:26 +0000134 action = SCons.Action.Action(command, "$CODEGENCOMSTR")
135 code = env.Command(target, source, action)
José Fonseca97e2c5a2009-12-31 17:58:56 +0000136
137 # Explicitly mark that the generated code depends on the generator,
138 # and on implicitly imported python modules
Giuseppe Bilotta1b62b472016-05-25 07:32:08 -0600139 path = (script_src.get_dir(),) if scons_version < (2, 5, 0) else lambda x: script_src
José Fonseca97e2c5a2009-12-31 17:58:56 +0000140 deps = [script_src]
141 deps += script_src.get_implicit_deps(env, python_scanner, path)
142 env.Depends(code, deps)
143
144 # Running the Python script causes .pyc files to be generated in the
145 # source directory. When we clean up, they should go too. So add side
146 # effects for .pyc files
147 for dep in deps:
148 pyc = env.File(str(dep) + 'c')
149 env.SideEffect(pyc, code)
150
151 return code
152
153
154def createCodeGenerateMethod(env):
155 env.Append(SCANNERS = python_scanner)
156 env.AddMethod(code_generate, 'CodeGenerate')
157
158
José Fonseca235225e2011-06-30 17:36:37 +0100159def _pkg_check_modules(env, name, modules):
160 '''Simple wrapper for pkg-config.'''
161
162 env['HAVE_' + name] = False
163
164 # For backwards compatability
165 env[name.lower()] = False
166
167 if env['platform'] == 'windows':
168 return
169
170 if not env.Detect('pkg-config'):
171 return
172
173 if subprocess.call(["pkg-config", "--exists", ' '.join(modules)]) != 0:
174 return
175
José Fonseca2470e912012-02-07 11:17:35 +0000176 # Strip version expressions from modules
177 modules = [module.split(' ', 1)[0] for module in modules]
178
José Fonseca235225e2011-06-30 17:36:37 +0100179 # Other flags may affect the compilation of unrelated targets, so store
180 # them with a prefix, (e.g., XXX_CFLAGS, XXX_LIBS, etc)
181 try:
182 flags = env.ParseFlags('!pkg-config --cflags --libs ' + ' '.join(modules))
183 except OSError:
184 return
185 prefix = name + '_'
186 for flag_name, flag_value in flags.iteritems():
187 assert '_' not in flag_name
188 env[prefix + flag_name] = flag_value
189
190 env['HAVE_' + name] = True
191
192def pkg_check_modules(env, name, modules):
193
José Fonseca2470e912012-02-07 11:17:35 +0000194 sys.stdout.write('Checking for %s (%s)...' % (name, ' '.join(modules)))
José Fonseca235225e2011-06-30 17:36:37 +0100195 _pkg_check_modules(env, name, modules)
196 result = env['HAVE_' + name]
197 sys.stdout.write(' %s\n' % ['no', 'yes'][int(bool(result))])
198
199 # XXX: For backwards compatability
200 env[name.lower()] = result
201
202
203def pkg_use_modules(env, names):
204 '''Search for all environment flags that match NAME_FOO and append them to
205 the FOO environment variable.'''
206
207 names = env.Flatten(names)
208
209 for name in names:
210 prefix = name + '_'
211
212 if not 'HAVE_' + name in env:
José Fonsecaf8aeb1c2011-09-20 20:40:05 +0100213 raise Exception('Attempt to use unknown module %s' % name)
José Fonseca235225e2011-06-30 17:36:37 +0100214
215 if not env['HAVE_' + name]:
José Fonsecaf8aeb1c2011-09-20 20:40:05 +0100216 raise Exception('Attempt to use unavailable module %s' % name)
José Fonseca235225e2011-06-30 17:36:37 +0100217
218 flags = {}
219 for flag_name, flag_value in env.Dictionary().iteritems():
220 if flag_name.startswith(prefix):
221 flag_name = flag_name[len(prefix):]
222 if '_' not in flag_name:
223 flags[flag_name] = flag_value
224 if flags:
225 env.MergeFlags(flags)
226
227
228def createPkgConfigMethods(env):
229 env.AddMethod(pkg_check_modules, 'PkgCheckModules')
230 env.AddMethod(pkg_use_modules, 'PkgUseModules')
231
232
Chia-I Wu582b5d82011-08-18 17:12:29 +0800233def parse_source_list(env, filename, names=None):
234 # parse the source list file
235 parser = source_list.SourceListParser()
236 src = env.File(filename).srcnode()
José Fonsecaea8dcfc2012-08-14 12:18:45 +0100237
José Fonseca50dec632012-08-15 19:24:58 +0100238 cur_srcdir = env.Dir('.').srcnode().abspath
239 top_srcdir = env.Dir('#').abspath
240 top_builddir = os.path.join(top_srcdir, env['build_dir'])
241
José Fonseca06424372013-01-22 20:54:17 +0000242 # Normalize everything to / slashes
243 cur_srcdir = cur_srcdir.replace('\\', '/')
244 top_srcdir = top_srcdir.replace('\\', '/')
245 top_builddir = top_builddir.replace('\\', '/')
246
José Fonseca50dec632012-08-15 19:24:58 +0100247 # Populate the symbol table of the Makefile parser.
248 parser.add_symbol('top_srcdir', top_srcdir)
249 parser.add_symbol('top_builddir', top_builddir)
José Fonsecaea8dcfc2012-08-14 12:18:45 +0100250
Chia-I Wu582b5d82011-08-18 17:12:29 +0800251 sym_table = parser.parse(src.abspath)
252
253 if names:
254 if isinstance(names, basestring):
255 names = [names]
256
257 symbols = names
258 else:
259 symbols = sym_table.keys()
260
261 # convert the symbol table to source lists
262 src_lists = {}
263 for sym in symbols:
264 val = sym_table[sym]
José Fonseca50dec632012-08-15 19:24:58 +0100265 srcs = []
266 for f in val.split():
267 if f:
268 # Process source paths
269 if f.startswith(top_builddir + '/src'):
José Fonseca06424372013-01-22 20:54:17 +0000270 # Automake puts build output on a `src` subdirectory, but
271 # SCons does not, so strip it here.
José Fonseca50dec632012-08-15 19:24:58 +0100272 f = top_builddir + f[len(top_builddir + '/src'):]
273 if f.startswith(cur_srcdir + '/'):
274 # Prefer relative source paths, as absolute files tend to
275 # cause duplicate actions.
276 f = f[len(cur_srcdir + '/'):]
Jose Fonsecad4a1f3f2014-08-13 20:33:35 +0100277 # do not include any headers
278 if f.endswith('.h'):
279 continue
José Fonseca50dec632012-08-15 19:24:58 +0100280 srcs.append(f)
281
282 src_lists[sym] = srcs
Chia-I Wu582b5d82011-08-18 17:12:29 +0800283
284 # if names are given, concatenate the lists
285 if names:
286 srcs = []
287 for name in names:
288 srcs.extend(src_lists[name])
289
290 return srcs
291 else:
292 return src_lists
293
294def createParseSourceListMethod(env):
295 env.AddMethod(parse_source_list, 'ParseSourceList')
296
297
José Fonseca97e2c5a2009-12-31 17:58:56 +0000298def generate(env):
299 """Common environment generation code"""
300
José Fonsecac7bd0fa2011-06-17 18:42:39 +0100301 verbose = env.get('verbose', False) or not env.get('quiet', True)
302 if not verbose:
José Fonseca97e2c5a2009-12-31 17:58:56 +0000303 quietCommandLines(env)
304
305 # Custom builders and methods
306 createConvenienceLibBuilder(env)
307 createCodeGenerateMethod(env)
José Fonseca235225e2011-06-30 17:36:37 +0100308 createPkgConfigMethods(env)
Chia-I Wu582b5d82011-08-18 17:12:29 +0800309 createParseSourceListMethod(env)
José Fonseca97e2c5a2009-12-31 17:58:56 +0000310
311 # for debugging
312 #print env.Dump()
313
314
315def exists(env):
316 return 1