3 # Copyright 2001 Google Inc. All Rights Reserved.
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 """Script that generates the build.ninja for ninja itself.
19 Projects that use ninja themselves should either write a similar script
20 or use a meta-build system that supports Ninja output."""
22 from __future__ import print_function
24 from optparse import OptionParser
27 import platform_helper
28 sys.path.insert(0, 'misc')
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',
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()
57 print('ERROR: extra unparsed command-line arguments:', args)
60 platform = platform_helper.Platform(options.platform)
62 host = platform_helper.Platform(options.host)
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__) + '.')
73 n.variable('ninja_required_version', '1.3')
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)
81 config_str = ' '.join([k + '=' + configure_env[k] for k in configure_env])
82 n.variable('configure_env', config_str + '$ ')
85 CXX = configure_env.get('CXX', 'g++')
87 if platform.is_msvc():
92 return os.path.join('src', filename)
94 return os.path.join('$builddir', 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)
102 if platform.is_windows():
104 n.build(name, 'phony', exe)
108 n.variable('builddir', 'build')
109 n.variable('cxx', CXX)
110 if platform.is_msvc():
111 n.variable('ar', 'link')
113 n.variable('ar', configure_env.get('AR', 'ar'))
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.
124 '/GR-', # Disable RTTI.
125 # Disable size_t -> int truncation warning.
126 # We never have strings or arrays larger than 2**31.
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():
133 ldflags = ['/DEBUG', '/libpath:$builddir']
134 if not options.debug:
135 cflags += ['/Ox', '/DNDEBUG', '/GL']
136 ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
138 cflags = ['-g', '-Wall', '-Wextra',
140 '-Wno-unused-parameter',
143 '-fvisibility=hidden', '-pipe',
144 '-Wno-missing-field-initializers',
145 '-DNINJA_PYTHON="%s"' % options.with_python]
147 cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
148 cflags.remove('-fno-rtti') # Needed for above pedanticness.
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']
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():
166 if options.profile == 'gmon':
168 ldflags.append('-pg')
169 elif options.profile == 'pprof':
170 cflags.append('-fno-omit-frame-pointer')
171 libs.extend(['-Wl,--no-as-needed', '-lprofiler'])
173 if (platform.is_linux() or platform.is_openbsd() or platform.is_bitrig()) and \
174 not options.force_pselect:
175 cflags.append('-DUSE_PPOLL')
177 def shell_escape(str):
178 """Escape str such that it's interpreted as a single argument by
181 # This isn't complete, but it's just enough to make NINJA_PYTHON work.
182 if platform.is_windows():
185 return "'%s'" % str.replace("'", "\\'")
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))
196 if platform.is_msvc():
198 command='$cxx /showIncludes $cflags -c $in /Fo$out',
199 description='CXX $out',
203 command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
206 description='CXX $out')
211 command='lib /nologo /ltcg /out:$out $in',
212 description='LIB $out')
213 elif host.is_mingw():
215 command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
216 description='AR $out')
219 command='rm -f $out && $ar crs $out $in',
220 description='AR $out')
223 if platform.is_msvc():
225 command='$cxx $in $libs /nologo /link $ldflags /out:$out',
226 description='LINK $out')
229 command='$cxx $ldflags -o $out $in $libs',
230 description='LINK $out')
235 if not platform.is_windows() and not platform.is_solaris():
236 n.comment('browse_py.h is used to inline browse.py.')
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')])
245 objs += cxx('browse', order_only=built('browse_py.h'))
248 n.comment('the depfile parser and ninja lexers are generated using re2c.')
252 proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
253 return int(proc.communicate()[0], 10) >= 1103
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'))
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.")
268 n.comment('Core source files all build into ninja library.')
269 for name in ['build',
288 if platform.is_windows():
289 for name in ['subprocess-win32',
290 'includes_normalize-win32',
292 'msvc_helper_main-win32']:
294 if platform.is_msvc():
295 objs += cxx('minidump-win32')
298 objs += cxx('subprocess-posix')
299 if platform.is_msvc():
300 ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
302 ninja_lib = n.build(built('libninja.a'), 'ar', objs)
305 if platform.is_msvc():
306 libs.append('ninja.lib')
308 libs.append('-lninja')
312 n.comment('Main executable is library plus main() function.')
314 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
315 variables=[('libs', libs)])
319 n.comment('Tests all build into ninja_test executable.')
322 test_cflags = cflags + ['-DGTEST_HAS_RTTI=0']
326 if options.with_gtest:
327 path = options.with_gtest
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
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)])
341 test_cflags.append('-I%s' % os.path.join(path, 'include'))
343 # Use gtest from system.
344 if platform.is_msvc():
345 test_libs.extend(['gtest_main.lib', 'gtest.lib'])
347 test_libs.extend(['-lgtest_main', '-lgtest'])
349 n.variable('test_cflags', test_cflags)
350 for name in ['build_log_test',
353 'depfile_parser_test',
355 'disk_interface_test',
356 'edit_distance_test',
359 'manifest_parser_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)])
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)])
376 all_targets += ninja_test
379 n.comment('Ancillary executables.')
380 objs = cxx('parser_perftest')
381 all_targets += n.build(binary('parser_perftest'), 'link', objs,
382 implicit=ninja_lib, variables=[('libs', libs)])
383 objs = cxx('build_log_perftest')
384 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
385 implicit=ninja_lib, variables=[('libs', libs)])
386 objs = cxx('canon_perftest')
387 all_targets += n.build(binary('canon_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)])
394 n.comment('Generate a graph using the "graph" tool.')
396 command='./ninja -t graph all > $out')
398 command='dot -Tpng $in > $out')
399 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
400 n.build('graph.png', 'gengraph', dot)
403 n.comment('Generate the manual using asciidoc.')
405 command='asciidoc -b docbook -d book -o $out $in',
406 description='ASCIIDOC $out')
408 command='xsltproc --nonet doc/docbook.xsl $in > $out',
409 description='XSLTPROC $out')
410 xml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
411 manual = n.build(doc('manual.html'), 'xsltproc', xml,
412 implicit=doc('style.css'))
413 n.build('manual', 'phony',
417 n.comment('Generate Doxygen.')
419 command='doxygen $in',
420 description='DOXYGEN $in')
421 n.variable('doxygen_mainpage_generator',
422 src('gen_doxygen_mainpage.sh'))
423 n.rule('doxygen_mainpage',
424 command='$doxygen_mainpage_generator $in > $out',
425 description='DOXYGEN_MAINPAGE $out')
426 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
427 ['README', 'COPYING'],
428 implicit=['$doxygen_mainpage_generator'])
429 n.build('doxygen', 'doxygen', doc('doxygen.config'),
433 if not host.is_mingw():
434 n.comment('Regenerate build files if build script changes.')
436 command='${configure_env}%s configure.py $configure_args' %
439 n.build('build.ninja', 'configure',
440 implicit=['configure.py', os.path.normpath('misc/ninja_syntax.py')])
447 n.comment('Packaging')
449 command="misc/packaging/rpmbuild.sh",
450 description='Building rpms..')
451 n.build('rpm', 'rpmbuild')
454 n.build('all', 'phony', all_targets)
456 print('wrote %s.' % BUILD_FILENAME)