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