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