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
30 import platform_helper
31 sys.path.insert(0, 'misc')
37 """API shim for ninja_syntax.Writer that instead runs the commands.
39 Used to bootstrap Ninja from scratch. In --bootstrap mode this
40 class is used to execute all the commands to build an executable.
41 It also proxies all calls to an underlying ninja_syntax.Writer, to
42 behave like non-bootstrap mode.
44 def __init__(self, writer):
46 # Map of variable name => expanded variable value.
48 # Map of rule name => dict of rule attributes.
53 def comment(self, text):
54 return self.writer.comment(text)
57 return self.writer.newline()
59 def variable(self, key, val):
60 self.vars[key] = self._expand(val)
61 return self.writer.variable(key, val)
63 def rule(self, name, **kwargs):
64 self.rules[name] = kwargs
65 return self.writer.rule(name, **kwargs)
67 def build(self, outputs, rule, inputs=None, **kwargs):
68 ruleattr = self.rules[rule]
69 cmd = ruleattr.get('command')
70 if cmd is None: # A phony rule, for example.
73 # Implement just enough of Ninja variable expansion etc. to
74 # make the bootstrap build work.
76 'in': self._expand_paths(inputs),
77 'out': self._expand_paths(outputs)
79 for key, val in kwargs.get('variables', []):
80 local_vars[key] = ' '.join(ninja_syntax.as_list(val))
82 self._run_command(self._expand(cmd, local_vars))
84 return self.writer.build(outputs, rule, inputs, **kwargs)
86 def default(self, paths):
87 return self.writer.default(paths)
89 def _expand_paths(self, paths):
90 """Expand $vars in an array of paths, e.g. from a 'build' block."""
91 paths = ninja_syntax.as_list(paths)
92 return ' '.join(map(self._expand, paths))
94 def _expand(self, str, local_vars={}):
95 """Expand $vars in a string."""
96 return ninja_syntax.expand(str, self.vars, local_vars)
98 def _run_command(self, cmdline):
99 """Run a subcommand, quietly. Prints the full command on error."""
101 subprocess.check_call(cmdline, shell=True)
102 except subprocess.CalledProcessError, e:
103 print('when running: ', cmdline)
107 parser = OptionParser()
108 profilers = ['gmon', 'pprof']
109 parser.add_option('--bootstrap', action='store_true',
110 help='bootstrap a ninja binary from nothing')
111 parser.add_option('--platform',
112 help='target platform (' +
113 '/'.join(platform_helper.platforms()) + ')',
114 choices=platform_helper.platforms())
115 parser.add_option('--host',
116 help='host platform (' +
117 '/'.join(platform_helper.platforms()) + ')',
118 choices=platform_helper.platforms())
119 parser.add_option('--debug', action='store_true',
120 help='enable debugging extras',)
121 parser.add_option('--profile', metavar='TYPE',
123 help='enable profiling (' + '/'.join(profilers) + ')',)
124 parser.add_option('--with-gtest', metavar='PATH', help='ignored')
125 parser.add_option('--with-python', metavar='EXE',
126 help='use EXE as the Python interpreter',
127 default=os.path.basename(sys.executable))
128 parser.add_option('--force-pselect', action='store_true',
129 help='ppoll() is used by default where available, '
130 'but some platforms may need to use pselect instead',)
131 (options, args) = parser.parse_args()
133 print('ERROR: extra unparsed command-line arguments:', args)
136 platform = platform_helper.Platform(options.platform)
138 host = platform_helper.Platform(options.host)
142 BUILD_FILENAME = 'build.ninja'
143 ninja_writer = ninja_syntax.Writer(open(BUILD_FILENAME, 'w'))
146 if options.bootstrap:
147 # Make the build directory.
152 # Wrap ninja_writer with the Bootstrapper, which also executes the
154 print('bootstrapping ninja...')
157 n.comment('This file is used to build ninja itself.')
158 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
161 n.variable('ninja_required_version', '1.3')
164 n.comment('The arguments passed to configure.py, for rerunning it.')
165 configure_args = sys.argv[1:]
166 if '--bootstrap' in configure_args:
167 configure_args.remove('--bootstrap')
168 n.variable('configure_args', ' '.join(configure_args))
169 env_keys = set(['CXX', 'AR', 'CFLAGS', 'LDFLAGS'])
170 configure_env = dict((k, os.environ[k]) for k in os.environ if k in env_keys)
172 config_str = ' '.join([k + '=' + pipes.quote(configure_env[k])
173 for k in configure_env])
174 n.variable('configure_env', config_str + '$ ')
177 CXX = configure_env.get('CXX', 'g++')
179 if platform.is_msvc():
184 return os.path.join('src', filename)
186 return os.path.join('$builddir', filename)
188 return os.path.join('doc', filename)
189 def cc(name, **kwargs):
190 return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
191 def cxx(name, **kwargs):
192 return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
194 if platform.is_windows():
196 n.build(name, 'phony', exe)
200 n.variable('builddir', 'build')
201 n.variable('cxx', CXX)
202 if platform.is_msvc():
203 n.variable('ar', 'link')
205 n.variable('ar', configure_env.get('AR', 'ar'))
207 if platform.is_msvc():
208 cflags = ['/showIncludes',
209 '/nologo', # Don't print startup banner.
210 '/Zi', # Create pdb with debug info.
211 '/W4', # Highest warning level.
212 '/WX', # Warnings as errors.
213 '/wd4530', '/wd4100', '/wd4706',
214 '/wd4512', '/wd4800', '/wd4702', '/wd4819',
215 # Disable warnings about passing "this" during initialization.
217 '/GR-', # Disable RTTI.
218 # Disable size_t -> int truncation warning.
219 # We never have strings or arrays larger than 2**31.
221 '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
222 '/D_VARIADIC_MAX=10',
223 '/DNINJA_PYTHON="%s"' % options.with_python]
224 if options.bootstrap:
225 # In bootstrap mode, we have no ninja process to catch /showIncludes
227 cflags.remove('/showIncludes')
228 if platform.msvc_needs_fs():
230 ldflags = ['/DEBUG', '/libpath:$builddir']
231 if not options.debug:
232 cflags += ['/Ox', '/DNDEBUG', '/GL']
233 ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
235 cflags = ['-g', '-Wall', '-Wextra',
237 '-Wno-unused-parameter',
240 '-fvisibility=hidden', '-pipe',
241 '-Wno-missing-field-initializers',
242 '-DNINJA_PYTHON="%s"' % options.with_python]
244 cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
245 cflags.remove('-fno-rtti') # Needed for above pedanticness.
247 cflags += ['-O2', '-DNDEBUG']
248 if 'clang' in os.path.basename(CXX):
249 cflags += ['-fcolor-diagnostics']
250 if platform.is_mingw():
251 cflags += ['-D_WIN32_WINNT=0x0501']
252 ldflags = ['-L$builddir']
255 if platform.is_mingw():
256 cflags.remove('-fvisibility=hidden');
257 ldflags.append('-static')
258 elif platform.is_solaris():
259 cflags.remove('-fvisibility=hidden')
260 elif platform.is_msvc():
263 if options.profile == 'gmon':
265 ldflags.append('-pg')
266 elif options.profile == 'pprof':
267 cflags.append('-fno-omit-frame-pointer')
268 libs.extend(['-Wl,--no-as-needed', '-lprofiler'])
270 if (platform.is_linux() or platform.is_openbsd() or platform.is_bitrig()) and \
271 not options.force_pselect:
272 cflags.append('-DUSE_PPOLL')
274 have_browse = not platform.is_windows() and not platform.is_solaris()
276 cflags.append('-DNINJA_HAVE_BROWSE')
278 def shell_escape(str):
279 """Escape str such that it's interpreted as a single argument by
282 # This isn't complete, but it's just enough to make NINJA_PYTHON work.
283 if platform.is_windows():
286 return "'%s'" % str.replace("'", "\\'")
289 if 'CFLAGS' in configure_env:
290 cflags.append(configure_env['CFLAGS'])
291 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
292 if 'LDFLAGS' in configure_env:
293 ldflags.append(configure_env['LDFLAGS'])
294 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
297 if platform.is_msvc():
299 command='$cxx $cflags -c $in /Fo$out',
300 description='CXX $out',
301 deps='msvc' # /showIncludes is included in $cflags.
305 command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
308 description='CXX $out')
313 command='lib /nologo /ltcg /out:$out $in',
314 description='LIB $out')
315 elif host.is_mingw():
317 command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
318 description='AR $out')
321 command='rm -f $out && $ar crs $out $in',
322 description='AR $out')
325 if platform.is_msvc():
327 command='$cxx $in $libs /nologo /link $ldflags /out:$out',
328 description='LINK $out')
331 command='$cxx $ldflags -o $out $in $libs',
332 description='LINK $out')
338 n.comment('browse_py.h is used to inline browse.py.')
340 command='src/inline.sh $varname < $in > $out',
341 description='INLINE $out')
342 n.build(built('browse_py.h'), 'inline', src('browse.py'),
343 implicit='src/inline.sh',
344 variables=[('varname', 'kBrowsePy')])
347 objs += cxx('browse', order_only=built('browse_py.h'))
350 n.comment('the depfile parser and ninja lexers are generated using re2c.')
353 proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
354 return int(proc.communicate()[0], 10) >= 1103
359 command='re2c -b -i --no-generation-date -o $out $in',
360 description='RE2C $out')
361 # Generate the .cc files in the source directory so we can check them in.
362 n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
363 n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
365 print("warning: A compatible version of re2c (>= 0.11.3) was not found; "
366 "changes to src/*.in.cc will not affect your build.")
369 n.comment('Core source files all build into ninja library.')
370 for name in ['build',
389 if platform.is_windows():
390 for name in ['subprocess-win32',
391 'includes_normalize-win32',
393 'msvc_helper_main-win32']:
395 if platform.is_msvc():
396 objs += cxx('minidump-win32')
399 objs += cxx('subprocess-posix')
400 if platform.is_msvc():
401 ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
403 ninja_lib = n.build(built('libninja.a'), 'ar', objs)
406 if platform.is_msvc():
407 libs.append('ninja.lib')
409 libs.append('-lninja')
413 n.comment('Main executable is library plus main() function.')
415 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
416 variables=[('libs', libs)])
420 if options.bootstrap:
421 # We've built the ninja binary. Don't run any more commands
422 # through the bootstrap executor, but continue writing the
426 n.comment('Tests all build into ninja_test executable.')
431 for name in ['build_log_test',
434 'depfile_parser_test',
436 'disk_interface_test',
437 'edit_distance_test',
440 'manifest_parser_test',
447 if platform.is_windows():
448 for name in ['includes_normalize_test', 'msvc_helper_test']:
451 if not platform.is_windows():
452 test_libs.append('-lpthread')
453 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
454 variables=[('libs', test_libs)])
456 all_targets += ninja_test
459 n.comment('Ancillary executables.')
460 objs = cxx('build_log_perftest')
461 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
462 implicit=ninja_lib, variables=[('libs', libs)])
463 objs = cxx('canon_perftest')
464 all_targets += n.build(binary('canon_perftest'), 'link', objs,
465 implicit=ninja_lib, variables=[('libs', libs)])
466 objs = cxx('depfile_parser_perftest')
467 all_targets += n.build(binary('depfile_parser_perftest'), 'link', objs,
468 implicit=ninja_lib, variables=[('libs', libs)])
469 objs = cxx('hash_collision_bench')
470 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
471 implicit=ninja_lib, variables=[('libs', libs)])
472 objs = cxx('manifest_parser_perftest')
473 all_targets += n.build(binary('manifest_parser_perftest'), 'link', objs,
474 implicit=ninja_lib, variables=[('libs', libs)])
477 n.comment('Generate a graph using the "graph" tool.')
479 command='./ninja -t graph all > $out')
481 command='dot -Tpng $in > $out')
482 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
483 n.build('graph.png', 'gengraph', dot)
486 n.comment('Generate the manual using asciidoc.')
488 command='asciidoc -b docbook -d book -o $out $in',
489 description='ASCIIDOC $out')
491 command='xsltproc --nonet doc/docbook.xsl $in > $out',
492 description='XSLTPROC $out')
493 xml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
494 manual = n.build(doc('manual.html'), 'xsltproc', xml,
495 implicit=doc('style.css'))
496 n.build('manual', 'phony',
500 n.comment('Generate Doxygen.')
502 command='doxygen $in',
503 description='DOXYGEN $in')
504 n.variable('doxygen_mainpage_generator',
505 src('gen_doxygen_mainpage.sh'))
506 n.rule('doxygen_mainpage',
507 command='$doxygen_mainpage_generator $in > $out',
508 description='DOXYGEN_MAINPAGE $out')
509 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
510 ['README', 'COPYING'],
511 implicit=['$doxygen_mainpage_generator'])
512 n.build('doxygen', 'doxygen', doc('doxygen.config'),
516 if not host.is_mingw():
517 n.comment('Regenerate build files if build script changes.')
519 command='${configure_env}%s configure.py $configure_args' %
522 n.build('build.ninja', 'configure',
523 implicit=['configure.py', os.path.normpath('misc/ninja_syntax.py')])
530 n.comment('Packaging')
532 command="misc/packaging/rpmbuild.sh",
533 description='Building rpms..')
534 n.build('rpm', 'rpmbuild')
537 n.build('all', 'phony', all_targets)
540 print('wrote %s.' % BUILD_FILENAME)
542 if options.bootstrap:
543 print('bootstrap complete. rebuilding...')
544 if platform.is_windows():
545 bootstrap_exe = 'ninja.bootstrap.exe'
546 if os.path.exists(bootstrap_exe):
547 os.unlink(bootstrap_exe)
548 os.rename('ninja.exe', bootstrap_exe)
549 subprocess.check_call('ninja.bootstrap.exe', shell=True)
551 subprocess.check_call('./ninja', shell=True)