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
28 import platform_helper
29 sys.path.insert(0, 'misc')
33 parser = OptionParser()
34 profilers = ['gmon', 'pprof']
35 parser.add_option('--platform',
36 help='target platform (' +
37 '/'.join(platform_helper.platforms()) + ')',
38 choices=platform_helper.platforms())
39 parser.add_option('--host',
40 help='host platform (' +
41 '/'.join(platform_helper.platforms()) + ')',
42 choices=platform_helper.platforms())
43 parser.add_option('--debug', action='store_true',
44 help='enable debugging extras',)
45 parser.add_option('--profile', metavar='TYPE',
47 help='enable profiling (' + '/'.join(profilers) + ')',)
48 parser.add_option('--with-gtest', metavar='PATH', help='ignored')
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 + '=' + pipes.quote(configure_env[k])
82 for k in configure_env])
83 n.variable('configure_env', config_str + '$ ')
86 CXX = configure_env.get('CXX', 'g++')
88 if platform.is_msvc():
93 return os.path.join('src', filename)
95 return os.path.join('$builddir', filename)
97 return os.path.join('doc', filename)
98 def cc(name, **kwargs):
99 return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
100 def cxx(name, **kwargs):
101 return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
103 if platform.is_windows():
105 n.build(name, 'phony', exe)
109 n.variable('builddir', 'build')
110 n.variable('cxx', CXX)
111 if platform.is_msvc():
112 n.variable('ar', 'link')
114 n.variable('ar', configure_env.get('AR', 'ar'))
116 if platform.is_msvc():
117 cflags = ['/nologo', # Don't print startup banner.
118 '/Zi', # Create pdb with debug info.
119 '/W4', # Highest warning level.
120 '/WX', # Warnings as errors.
121 '/wd4530', '/wd4100', '/wd4706',
122 '/wd4512', '/wd4800', '/wd4702', '/wd4819',
123 # Disable warnings about passing "this" during initialization.
125 '/GR-', # Disable RTTI.
126 # Disable size_t -> int truncation warning.
127 # We never have strings or arrays larger than 2**31.
129 '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
130 '/D_VARIADIC_MAX=10',
131 '/DNINJA_PYTHON="%s"' % options.with_python]
132 if platform.msvc_needs_fs():
134 ldflags = ['/DEBUG', '/libpath:$builddir']
135 if not options.debug:
136 cflags += ['/Ox', '/DNDEBUG', '/GL']
137 ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
139 cflags = ['-g', '-Wall', '-Wextra',
141 '-Wno-unused-parameter',
144 '-fvisibility=hidden', '-pipe',
145 '-Wno-missing-field-initializers',
146 '-DNINJA_PYTHON="%s"' % options.with_python]
148 cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
149 cflags.remove('-fno-rtti') # Needed for above pedanticness.
151 cflags += ['-O2', '-DNDEBUG']
152 if 'clang' in os.path.basename(CXX):
153 cflags += ['-fcolor-diagnostics']
154 if platform.is_mingw():
155 cflags += ['-D_WIN32_WINNT=0x0501']
156 ldflags = ['-L$builddir']
159 if platform.is_mingw():
160 cflags.remove('-fvisibility=hidden');
161 ldflags.append('-static')
162 elif platform.is_sunos5():
163 cflags.remove('-fvisibility=hidden')
164 elif platform.is_msvc():
167 if options.profile == 'gmon':
169 ldflags.append('-pg')
170 elif options.profile == 'pprof':
171 cflags.append('-fno-omit-frame-pointer')
172 libs.extend(['-Wl,--no-as-needed', '-lprofiler'])
174 if (platform.is_linux() or platform.is_openbsd() or platform.is_bitrig()) and \
175 not options.force_pselect:
176 cflags.append('-DUSE_PPOLL')
178 have_browse = not platform.is_windows() and not platform.is_solaris()
180 cflags.append('-DNINJA_HAVE_BROWSE')
182 def shell_escape(str):
183 """Escape str such that it's interpreted as a single argument by
186 # This isn't complete, but it's just enough to make NINJA_PYTHON work.
187 if platform.is_windows():
190 return "'%s'" % str.replace("'", "\\'")
193 if 'CFLAGS' in configure_env:
194 cflags.append(configure_env['CFLAGS'])
195 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
196 if 'LDFLAGS' in configure_env:
197 ldflags.append(configure_env['LDFLAGS'])
198 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
201 if platform.is_msvc():
203 command='$cxx /showIncludes $cflags -c $in /Fo$out',
204 description='CXX $out',
208 command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
211 description='CXX $out')
216 command='lib /nologo /ltcg /out:$out $in',
217 description='LIB $out')
218 elif host.is_mingw():
220 command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
221 description='AR $out')
224 command='rm -f $out && $ar crs $out $in',
225 description='AR $out')
228 if platform.is_msvc():
230 command='$cxx $in $libs /nologo /link $ldflags /out:$out',
231 description='LINK $out')
234 command='$cxx $ldflags -o $out $in $libs',
235 description='LINK $out')
241 n.comment('browse_py.h is used to inline browse.py.')
243 command='src/inline.sh $varname < $in > $out',
244 description='INLINE $out')
245 n.build(built('browse_py.h'), 'inline', src('browse.py'),
246 implicit='src/inline.sh',
247 variables=[('varname', 'kBrowsePy')])
250 objs += cxx('browse', order_only=built('browse_py.h'))
253 n.comment('the depfile parser and ninja lexers are generated using re2c.')
257 proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
258 return int(proc.communicate()[0], 10) >= 1103
263 command='re2c -b -i --no-generation-date -o $out $in',
264 description='RE2C $out')
265 # Generate the .cc files in the source directory so we can check them in.
266 n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
267 n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
269 print("warning: A compatible version of re2c (>= 0.11.3) was not found; "
270 "changes to src/*.in.cc will not affect your build.")
273 n.comment('Core source files all build into ninja library.')
274 for name in ['build',
293 if platform.is_windows():
294 for name in ['subprocess-win32',
295 'includes_normalize-win32',
297 'msvc_helper_main-win32']:
299 if platform.is_msvc():
300 objs += cxx('minidump-win32')
303 objs += cxx('subprocess-posix')
304 if platform.is_msvc():
305 ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
307 ninja_lib = n.build(built('libninja.a'), 'ar', objs)
310 if platform.is_msvc():
311 libs.append('ninja.lib')
313 libs.append('-lninja')
317 n.comment('Main executable is library plus main() function.')
319 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
320 variables=[('libs', libs)])
324 n.comment('Tests all build into ninja_test executable.')
329 for name in ['build_log_test',
332 'depfile_parser_test',
334 'disk_interface_test',
335 'edit_distance_test',
338 'manifest_parser_test',
345 if platform.is_windows():
346 for name in ['includes_normalize_test', 'msvc_helper_test']:
349 if not platform.is_windows():
350 test_libs.append('-lpthread')
351 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
352 variables=[('libs', test_libs)])
354 all_targets += ninja_test
357 n.comment('Ancillary executables.')
358 objs = cxx('build_log_perftest')
359 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
360 implicit=ninja_lib, variables=[('libs', libs)])
361 objs = cxx('canon_perftest')
362 all_targets += n.build(binary('canon_perftest'), 'link', objs,
363 implicit=ninja_lib, variables=[('libs', libs)])
364 objs = cxx('depfile_parser_perftest')
365 all_targets += n.build(binary('depfile_parser_perftest'), 'link', objs,
366 implicit=ninja_lib, variables=[('libs', libs)])
367 objs = cxx('hash_collision_bench')
368 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
369 implicit=ninja_lib, variables=[('libs', libs)])
370 objs = cxx('manifest_parser_perftest')
371 all_targets += n.build(binary('manifest_parser_perftest'), 'link', objs,
372 implicit=ninja_lib, variables=[('libs', libs)])
375 n.comment('Generate a graph using the "graph" tool.')
377 command='./ninja -t graph all > $out')
379 command='dot -Tpng $in > $out')
380 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
381 n.build('graph.png', 'gengraph', dot)
384 n.comment('Generate the manual using asciidoc.')
386 command='asciidoc -b docbook -d book -o $out $in',
387 description='ASCIIDOC $out')
389 command='xsltproc --nonet doc/docbook.xsl $in > $out',
390 description='XSLTPROC $out')
391 xml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
392 manual = n.build(doc('manual.html'), 'xsltproc', xml,
393 implicit=doc('style.css'))
394 n.build('manual', 'phony',
398 n.comment('Generate Doxygen.')
400 command='doxygen $in',
401 description='DOXYGEN $in')
402 n.variable('doxygen_mainpage_generator',
403 src('gen_doxygen_mainpage.sh'))
404 n.rule('doxygen_mainpage',
405 command='$doxygen_mainpage_generator $in > $out',
406 description='DOXYGEN_MAINPAGE $out')
407 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
408 ['README', 'COPYING'],
409 implicit=['$doxygen_mainpage_generator'])
410 n.build('doxygen', 'doxygen', doc('doxygen.config'),
414 if not host.is_mingw():
415 n.comment('Regenerate build files if build script changes.')
417 command='${configure_env}%s configure.py $configure_args' %
420 n.build('build.ninja', 'configure',
421 implicit=['configure.py', os.path.normpath('misc/ninja_syntax.py')])
428 n.comment('Packaging')
430 command="misc/packaging/rpmbuild.sh",
431 description='Building rpms..')
432 n.build('rpm', 'rpmbuild')
435 n.build('all', 'phony', all_targets)
437 print('wrote %s.' % BUILD_FILENAME)