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