share platform support between configure/bootstrap
[platform/upstream/ninja.git] / configure.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2001 Google Inc. All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 #     http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 """Script that generates the build.ninja for ninja itself.
18
19 Projects that use ninja themselves should either write a similar script
20 or use a meta-build system that supports Ninja output."""
21
22 from __future__ import print_function
23
24 from optparse import OptionParser
25 import os
26 import sys
27 import platform_helper
28 sys.path.insert(0, 'misc')
29
30 import ninja_syntax
31
32 parser = OptionParser()
33 profilers = ['gmon', 'pprof']
34 parser.add_option('--platform',
35                   help='target platform (' + '/'.join(platform_helper.platforms()) + ')',
36                   choices=platform_helper.platforms())
37 parser.add_option('--host',
38                   help='host platform (' + '/'.join(platform_helper.platforms()) + ')',
39                   choices=platform_helper.platforms())
40 parser.add_option('--debug', action='store_true',
41                   help='enable debugging extras',)
42 parser.add_option('--profile', metavar='TYPE',
43                   choices=profilers,
44                   help='enable profiling (' + '/'.join(profilers) + ')',)
45 parser.add_option('--with-gtest', metavar='PATH',
46                   help='use gtest unpacked in directory PATH')
47 parser.add_option('--with-python', metavar='EXE',
48                   help='use EXE as the Python interpreter',
49                   default=os.path.basename(sys.executable))
50 (options, args) = parser.parse_args()
51 if args:
52     print('ERROR: extra unparsed command-line arguments:', args)
53     sys.exit(1)
54
55 platform = platform_helper.Platform(options.platform)
56 if options.host:
57     host = platform_helper.Platform(options.host)
58 else:
59     host = platform
60
61 BUILD_FILENAME = 'build.ninja'
62 buildfile = open(BUILD_FILENAME, 'w')
63 n = ninja_syntax.Writer(buildfile)
64 n.comment('This file is used to build ninja itself.')
65 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
66 n.newline()
67
68 n.comment('The arguments passed to configure.py, for rerunning it.')
69 n.variable('configure_args', ' '.join(sys.argv[1:]))
70 env_keys = set(['CXX', 'AR', 'CFLAGS', 'LDFLAGS'])
71 configure_env = dict((k, os.environ[k]) for k in os.environ if k in env_keys)
72 if configure_env:
73     config_str = ' '.join([k + '=' + configure_env[k] for k in configure_env])
74     n.variable('configure_env', config_str + '$ ')
75 n.newline()
76
77 CXX = configure_env.get('CXX', 'g++')
78 objext = '.o'
79 if platform.is_msvc():
80     CXX = 'cl'
81     objext = '.obj'
82
83 def src(filename):
84     return os.path.join('src', filename)
85 def built(filename):
86     return os.path.join('$builddir', filename)
87 def doc(filename):
88     return os.path.join('doc', filename)
89 def cc(name, **kwargs):
90     return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
91 def cxx(name, **kwargs):
92     return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
93 def binary(name):
94     if platform.is_windows():
95         exe = name + '.exe'
96         n.build(name, 'phony', exe)
97         return exe
98     return name
99
100 n.variable('builddir', 'build')
101 n.variable('cxx', CXX)
102 if platform.is_msvc():
103     n.variable('ar', 'link')
104 else:
105     n.variable('ar', configure_env.get('AR', 'ar'))
106
107 if platform.is_msvc():
108     cflags = ['/nologo',  # Don't print startup banner.
109               '/Zi',  # Create pdb with debug info.
110               '/W4',  # Highest warning level.
111               '/WX',  # Warnings as errors.
112               '/wd4530', '/wd4100', '/wd4706',
113               '/wd4512', '/wd4800', '/wd4702', '/wd4819',
114               # Disable warnings about passing "this" during initialization.
115               '/wd4355',
116               '/GR-',  # Disable RTTI.
117               # Disable size_t -> int truncation warning.
118               # We never have strings or arrays larger than 2**31.
119               '/wd4267',
120               '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
121               '/D_VARIADIC_MAX=10',
122               '/DNINJA_PYTHON="%s"' % options.with_python]
123     ldflags = ['/DEBUG', '/libpath:$builddir']
124     if not options.debug:
125         cflags += ['/Ox', '/DNDEBUG', '/GL']
126         ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
127 else:
128     cflags = ['-g', '-Wall', '-Wextra',
129               '-Wno-deprecated',
130               '-Wno-unused-parameter',
131               '-fno-rtti',
132               '-fno-exceptions',
133               '-fvisibility=hidden', '-pipe',
134               '-Wno-missing-field-initializers',
135               '-DNINJA_PYTHON="%s"' % options.with_python]
136     if options.debug:
137         cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
138         cflags.remove('-fno-rtti')  # Needed for above pedanticness.
139     else:
140         cflags += ['-O2', '-DNDEBUG']
141     if 'clang' in os.path.basename(CXX):
142         cflags += ['-fcolor-diagnostics']
143     if platform.is_mingw():
144         cflags += ['-D_WIN32_WINNT=0x0501']
145     ldflags = ['-L$builddir']
146 libs = []
147
148 if platform.is_mingw():
149     cflags.remove('-fvisibility=hidden');
150     ldflags.append('-static')
151 elif platform.is_sunos5():
152     cflags.remove('-fvisibility=hidden')
153 elif platform.is_msvc():
154     pass
155 else:
156     if options.profile == 'gmon':
157         cflags.append('-pg')
158         ldflags.append('-pg')
159     elif options.profile == 'pprof':
160         cflags.append('-fno-omit-frame-pointer')
161         libs.extend(['-Wl,--no-as-needed', '-lprofiler'])
162
163 def shell_escape(str):
164     """Escape str such that it's interpreted as a single argument by
165     the shell."""
166
167     # This isn't complete, but it's just enough to make NINJA_PYTHON work.
168     if platform.is_windows():
169       return str
170     if '"' in str:
171         return "'%s'" % str.replace("'", "\\'")
172     return str
173
174 if 'CFLAGS' in configure_env:
175     cflags.append(configure_env['CFLAGS'])
176 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
177 if 'LDFLAGS' in configure_env:
178     ldflags.append(configure_env['LDFLAGS'])
179 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
180 n.newline()
181
182 if platform.is_msvc():
183     n.rule('cxx',
184         command='$cxx /showIncludes $cflags -c $in /Fo$out',
185         description='CXX $out',
186         deps='msvc')
187 else:
188     n.rule('cxx',
189         command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
190         depfile='$out.d',
191         deps='gcc',
192         description='CXX $out')
193 n.newline()
194
195 if host.is_msvc():
196     n.rule('ar',
197            command='lib /nologo /ltcg /out:$out $in',
198            description='LIB $out')
199 elif host.is_mingw():
200     n.rule('ar',
201            command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
202            description='AR $out')
203 else:
204     n.rule('ar',
205            command='rm -f $out && $ar crs $out $in',
206            description='AR $out')
207 n.newline()
208
209 if platform.is_msvc():
210     n.rule('link',
211         command='$cxx $in $libs /nologo /link $ldflags /out:$out',
212         description='LINK $out')
213 else:
214     n.rule('link',
215         command='$cxx $ldflags -o $out $in $libs',
216         description='LINK $out')
217 n.newline()
218
219 objs = []
220
221 if not platform.is_windows() and not platform.is_solaris():
222     n.comment('browse_py.h is used to inline browse.py.')
223     n.rule('inline',
224            command='src/inline.sh $varname < $in > $out',
225            description='INLINE $out')
226     n.build(built('browse_py.h'), 'inline', src('browse.py'),
227             implicit='src/inline.sh',
228             variables=[('varname', 'kBrowsePy')])
229     n.newline()
230
231     objs += cxx('browse', order_only=built('browse_py.h'))
232     n.newline()
233
234 n.comment('the depfile parser and ninja lexers are generated using re2c.')
235 def has_re2c():
236     import subprocess
237     try:
238         proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
239         return int(proc.communicate()[0], 10) >= 1103
240     except OSError:
241         return False
242 if has_re2c():
243     n.rule('re2c',
244            command='re2c -b -i --no-generation-date -o $out $in',
245            description='RE2C $out')
246     # Generate the .cc files in the source directory so we can check them in.
247     n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
248     n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
249 else:
250     print("warning: A compatible version of re2c (>= 0.11.3) was not found; "
251            "changes to src/*.in.cc will not affect your build.")
252 n.newline()
253
254 n.comment('Core source files all build into ninja library.')
255 for name in ['build',
256              'build_log',
257              'clean',
258              'depfile_parser',
259              'deps_log',
260              'disk_interface',
261              'edit_distance',
262              'eval_env',
263              'explain',
264              'graph',
265              'graphviz',
266              'lexer',
267              'line_printer',
268              'manifest_parser',
269              'metrics',
270              'state',
271              'util',
272              'version']:
273     objs += cxx(name)
274 if platform.is_windows():
275     for name in ['subprocess-win32',
276                  'includes_normalize-win32',
277                  'msvc_helper-win32',
278                  'msvc_helper_main-win32']:
279         objs += cxx(name)
280     if platform.is_msvc():
281         objs += cxx('minidump-win32')
282     objs += cc('getopt')
283 else:
284     objs += cxx('subprocess-posix')
285 if platform.is_msvc():
286     ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
287 else:
288     ninja_lib = n.build(built('libninja.a'), 'ar', objs)
289 n.newline()
290
291 if platform.is_msvc():
292     libs.append('ninja.lib')
293 else:
294     libs.append('-lninja')
295
296 all_targets = []
297
298 n.comment('Main executable is library plus main() function.')
299 objs = cxx('ninja')
300 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
301                 variables=[('libs', libs)])
302 n.newline()
303 all_targets += ninja
304
305 n.comment('Tests all build into ninja_test executable.')
306
307 variables = []
308 test_cflags = cflags + ['-DGTEST_HAS_RTTI=0']
309 test_ldflags = None
310 test_libs = libs
311 objs = []
312 if options.with_gtest:
313     path = options.with_gtest
314
315     gtest_all_incs = '-I%s -I%s' % (path, os.path.join(path, 'include'))
316     if platform.is_msvc():
317         gtest_cflags = '/nologo /EHsc /Zi /D_VARIADIC_MAX=10 ' + gtest_all_incs
318     else:
319         gtest_cflags = '-fvisibility=hidden ' + gtest_all_incs
320     objs += n.build(built('gtest-all' + objext), 'cxx',
321                     os.path.join(path, 'src', 'gtest-all.cc'),
322                     variables=[('cflags', gtest_cflags)])
323
324     test_cflags.append('-I%s' % os.path.join(path, 'include'))
325 else:
326     # Use gtest from system.
327     if platform.is_msvc():
328         test_libs.extend(['gtest_main.lib', 'gtest.lib'])
329     else:
330         test_libs.extend(['-lgtest_main', '-lgtest'])
331
332 n.variable('test_cflags', test_cflags)
333 for name in ['build_log_test',
334              'build_test',
335              'clean_test',
336              'depfile_parser_test',
337              'deps_log_test',
338              'disk_interface_test',
339              'edit_distance_test',
340              'graph_test',
341              'lexer_test',
342              'manifest_parser_test',
343              'ninja_test',
344              'state_test',
345              'subprocess_test',
346              'test',
347              'util_test']:
348     objs += cxx(name, variables=[('cflags', '$test_cflags')])
349 if platform.is_windows():
350     for name in ['includes_normalize_test', 'msvc_helper_test']:
351         objs += cxx(name, variables=[('cflags', test_cflags)])
352
353 if not platform.is_windows():
354     test_libs.append('-lpthread')
355 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
356                      variables=[('ldflags', test_ldflags),
357                                 ('libs', test_libs)])
358 n.newline()
359 all_targets += ninja_test
360
361
362 n.comment('Ancillary executables.')
363 objs = cxx('parser_perftest')
364 all_targets += n.build(binary('parser_perftest'), 'link', objs,
365                        implicit=ninja_lib, variables=[('libs', libs)])
366 objs = cxx('build_log_perftest')
367 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
368                        implicit=ninja_lib, variables=[('libs', libs)])
369 objs = cxx('canon_perftest')
370 all_targets += n.build(binary('canon_perftest'), 'link', objs,
371                        implicit=ninja_lib, variables=[('libs', libs)])
372 objs = cxx('hash_collision_bench')
373 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
374                               implicit=ninja_lib, variables=[('libs', libs)])
375 n.newline()
376
377 n.comment('Generate a graph using the "graph" tool.')
378 n.rule('gendot',
379        command='./ninja -t graph all > $out')
380 n.rule('gengraph',
381        command='dot -Tpng $in > $out')
382 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
383 n.build('graph.png', 'gengraph', dot)
384 n.newline()
385
386 n.comment('Generate the manual using asciidoc.')
387 n.rule('asciidoc',
388        command='asciidoc -b docbook -d book -o $out $in',
389        description='ASCIIDOC $out')
390 n.rule('xsltproc',
391        command='xsltproc --nonet doc/docbook.xsl $in > $out',
392        description='XSLTPROC $out')
393 xml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
394 manual = n.build(doc('manual.html'), 'xsltproc', xml,
395                  implicit=doc('style.css'))
396 n.build('manual', 'phony',
397         order_only=manual)
398 n.newline()
399
400 n.comment('Generate Doxygen.')
401 n.rule('doxygen',
402        command='doxygen $in',
403        description='DOXYGEN $in')
404 n.variable('doxygen_mainpage_generator',
405            src('gen_doxygen_mainpage.sh'))
406 n.rule('doxygen_mainpage',
407        command='$doxygen_mainpage_generator $in > $out',
408        description='DOXYGEN_MAINPAGE $out')
409 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
410                    ['README', 'COPYING'],
411                    implicit=['$doxygen_mainpage_generator'])
412 n.build('doxygen', 'doxygen', doc('doxygen.config'),
413         implicit=mainpage)
414 n.newline()
415
416 if not host.is_mingw():
417     n.comment('Regenerate build files if build script changes.')
418     n.rule('configure',
419            command='${configure_env}%s configure.py $configure_args' %
420                options.with_python,
421            generator=True)
422     n.build('build.ninja', 'configure',
423             implicit=['configure.py', os.path.normpath('misc/ninja_syntax.py')])
424     n.newline()
425
426 n.default(ninja)
427 n.newline()
428
429 if host.is_linux():
430     n.comment('Packaging')
431     n.rule('rpmbuild',
432            command="misc/packaging/rpmbuild.sh",
433            description='Building rpms..')
434     n.build('rpm', 'rpmbuild')
435     n.newline()
436
437 n.build('all', 'phony', all_targets)
438
439 print('wrote %s.' % BUILD_FILENAME)