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
31 sourcedir = os.path.dirname(os.path.realpath(__file__))
32 sys.path.insert(0, os.path.join(sourcedir, 'misc'))
36 class Platform(object):
37 """Represents a host/target platform and its specific build attributes."""
38 def __init__(self, platform):
39 self._platform = platform
40 if self._platform is not None:
42 self._platform = sys.platform
43 if self._platform.startswith('linux'):
44 self._platform = 'linux'
45 elif self._platform.startswith('freebsd'):
46 self._platform = 'freebsd'
47 elif self._platform.startswith('gnukfreebsd'):
48 self._platform = 'freebsd'
49 elif self._platform.startswith('openbsd'):
50 self._platform = 'openbsd'
51 elif self._platform.startswith('solaris') or self._platform == 'sunos5':
52 self._platform = 'solaris'
53 elif self._platform.startswith('mingw'):
54 self._platform = 'mingw'
55 elif self._platform.startswith('win'):
56 self._platform = 'msvc'
57 elif self._platform.startswith('bitrig'):
58 self._platform = 'bitrig'
59 elif self._platform.startswith('netbsd'):
60 self._platform = 'netbsd'
61 elif self._platform.startswith('aix'):
62 self._platform = 'aix'
65 def known_platforms():
66 return ['linux', 'darwin', 'freebsd', 'openbsd', 'solaris', 'sunos5',
67 'mingw', 'msvc', 'gnukfreebsd', 'bitrig', 'netbsd', 'aix']
73 return self._platform == 'linux'
76 return self._platform == 'mingw'
79 return self._platform == 'msvc'
81 def msvc_needs_fs(self):
82 popen = subprocess.Popen(['cl', '/nologo', '/?'],
83 stdout=subprocess.PIPE,
84 stderr=subprocess.PIPE)
85 out, err = popen.communicate()
89 return self.is_mingw() or self.is_msvc()
92 return self._platform == 'solaris'
95 return self._platform == 'aix'
97 def uses_usr_local(self):
98 return self._platform in ('freebsd', 'openbsd', 'bitrig')
100 def supports_ppoll(self):
101 return self._platform in ('linux', 'openbsd', 'bitrig')
103 def supports_ninja_browse(self):
104 return (not self.is_windows()
105 and not self.is_solaris()
106 and not self.is_aix())
108 def can_rebuild_in_place(self):
109 return not (self.is_windows() or self.is_aix())
112 """API shim for ninja_syntax.Writer that instead runs the commands.
114 Used to bootstrap Ninja from scratch. In --bootstrap mode this
115 class is used to execute all the commands to build an executable.
116 It also proxies all calls to an underlying ninja_syntax.Writer, to
117 behave like non-bootstrap mode.
119 def __init__(self, writer, verbose=False):
121 self.verbose = verbose
122 # Map of variable name => expanded variable value.
124 # Map of rule name => dict of rule attributes.
129 def comment(self, text):
130 return self.writer.comment(text)
133 return self.writer.newline()
135 def variable(self, key, val):
136 self.vars[key] = self._expand(val)
137 return self.writer.variable(key, val)
139 def rule(self, name, **kwargs):
140 self.rules[name] = kwargs
141 return self.writer.rule(name, **kwargs)
143 def build(self, outputs, rule, inputs=None, **kwargs):
144 ruleattr = self.rules[rule]
145 cmd = ruleattr.get('command')
146 if cmd is None: # A phony rule, for example.
149 # Implement just enough of Ninja variable expansion etc. to
150 # make the bootstrap build work.
152 'in': self._expand_paths(inputs),
153 'out': self._expand_paths(outputs)
155 for key, val in kwargs.get('variables', []):
156 local_vars[key] = ' '.join(ninja_syntax.as_list(val))
158 self._run_command(self._expand(cmd, local_vars))
160 return self.writer.build(outputs, rule, inputs, **kwargs)
162 def default(self, paths):
163 return self.writer.default(paths)
165 def _expand_paths(self, paths):
166 """Expand $vars in an array of paths, e.g. from a 'build' block."""
167 paths = ninja_syntax.as_list(paths)
168 return ' '.join(map(self._shell_escape, (map(self._expand, paths))))
170 def _expand(self, str, local_vars={}):
171 """Expand $vars in a string."""
172 return ninja_syntax.expand(str, self.vars, local_vars)
174 def _shell_escape(self, path):
175 """Quote paths containing spaces."""
176 return '"%s"' % path if ' ' in path else path
178 def _run_command(self, cmdline):
179 """Run a subcommand, quietly. Prints the full command on error."""
183 subprocess.check_call(cmdline, shell=True)
184 except subprocess.CalledProcessError:
185 print('when running: ', cmdline)
189 parser = OptionParser()
190 profilers = ['gmon', 'pprof']
191 parser.add_option('--bootstrap', action='store_true',
192 help='bootstrap a ninja binary from nothing')
193 parser.add_option('--verbose', action='store_true',
194 help='enable verbose build')
195 parser.add_option('--platform',
196 help='target platform (' +
197 '/'.join(Platform.known_platforms()) + ')',
198 choices=Platform.known_platforms())
199 parser.add_option('--host',
200 help='host platform (' +
201 '/'.join(Platform.known_platforms()) + ')',
202 choices=Platform.known_platforms())
203 parser.add_option('--debug', action='store_true',
204 help='enable debugging extras',)
205 parser.add_option('--profile', metavar='TYPE',
207 help='enable profiling (' + '/'.join(profilers) + ')',)
208 parser.add_option('--with-gtest', metavar='PATH', help='ignored')
209 parser.add_option('--with-python', metavar='EXE',
210 help='use EXE as the Python interpreter',
211 default=os.path.basename(sys.executable))
212 parser.add_option('--force-pselect', action='store_true',
213 help='ppoll() is used by default where available, '
214 'but some platforms may need to use pselect instead',)
215 (options, args) = parser.parse_args()
217 print('ERROR: extra unparsed command-line arguments:', args)
220 platform = Platform(options.platform)
222 host = Platform(options.host)
226 BUILD_FILENAME = 'build.ninja'
227 ninja_writer = ninja_syntax.Writer(open(BUILD_FILENAME, 'w'))
230 if options.bootstrap:
231 # Make the build directory.
236 # Wrap ninja_writer with the Bootstrapper, which also executes the
238 print('bootstrapping ninja...')
239 n = Bootstrap(n, verbose=options.verbose)
241 n.comment('This file is used to build ninja itself.')
242 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
245 n.variable('ninja_required_version', '1.3')
248 n.comment('The arguments passed to configure.py, for rerunning it.')
249 configure_args = sys.argv[1:]
250 if '--bootstrap' in configure_args:
251 configure_args.remove('--bootstrap')
252 n.variable('configure_args', ' '.join(configure_args))
253 env_keys = set(['CXX', 'AR', 'CFLAGS', 'LDFLAGS'])
254 configure_env = dict((k, os.environ[k]) for k in os.environ if k in env_keys)
256 config_str = ' '.join([k + '=' + pipes.quote(configure_env[k])
257 for k in configure_env])
258 n.variable('configure_env', config_str + '$ ')
261 CXX = configure_env.get('CXX', 'g++')
263 if platform.is_msvc():
268 return os.path.join('$sourcedir', 'src', filename)
270 return os.path.join('$builddir', filename)
272 return os.path.join('$sourcedir', 'doc', filename)
273 def cc(name, **kwargs):
274 return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
275 def cxx(name, **kwargs):
276 return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
278 if platform.is_windows():
280 n.build(name, 'phony', exe)
284 n.variable('sourcedir', sourcedir)
285 n.variable('builddir', 'build')
286 n.variable('cxx', CXX)
287 if platform.is_msvc():
288 n.variable('ar', 'link')
290 n.variable('ar', configure_env.get('AR', 'ar'))
292 if platform.is_msvc():
293 cflags = ['/showIncludes',
294 '/nologo', # Don't print startup banner.
295 '/Zi', # Create pdb with debug info.
296 '/W4', # Highest warning level.
297 '/WX', # Warnings as errors.
298 '/wd4530', '/wd4100', '/wd4706',
299 '/wd4512', '/wd4800', '/wd4702', '/wd4819',
300 # Disable warnings about passing "this" during initialization.
302 # Disable warnings about ignored typedef in DbgHelp.h
304 '/GR-', # Disable RTTI.
305 # Disable size_t -> int truncation warning.
306 # We never have strings or arrays larger than 2**31.
308 '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
309 '/D_HAS_EXCEPTIONS=0',
310 '/DNINJA_PYTHON="%s"' % options.with_python]
311 if options.bootstrap:
312 # In bootstrap mode, we have no ninja process to catch /showIncludes
314 cflags.remove('/showIncludes')
315 if platform.msvc_needs_fs():
317 ldflags = ['/DEBUG', '/libpath:$builddir']
318 if not options.debug:
319 cflags += ['/Ox', '/DNDEBUG', '/GL']
320 ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
322 cflags = ['-g', '-Wall', '-Wextra',
324 '-Wno-unused-parameter',
327 '-fvisibility=hidden', '-pipe',
328 '-Wno-missing-field-initializers',
329 '-DNINJA_PYTHON="%s"' % options.with_python]
331 cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
332 cflags.remove('-fno-rtti') # Needed for above pedanticness.
334 cflags += ['-O2', '-DNDEBUG']
336 proc = subprocess.Popen(
337 [CXX, '-fdiagnostics-color', '-c', '-x', 'c++', '/dev/null',
339 stdout=open(os.devnull, 'wb'), stderr=subprocess.STDOUT)
341 cflags += ['-fdiagnostics-color']
344 if platform.is_mingw():
345 cflags += ['-D_WIN32_WINNT=0x0501']
346 ldflags = ['-L$builddir']
347 if platform.uses_usr_local():
348 cflags.append('-I/usr/local/include')
349 ldflags.append('-L/usr/local/lib')
353 if platform.is_mingw():
354 cflags.remove('-fvisibility=hidden');
355 ldflags.append('-static')
356 elif platform.is_solaris():
357 cflags.remove('-fvisibility=hidden')
358 elif platform.is_aix():
359 cflags.remove('-fvisibility=hidden')
360 elif platform.is_msvc():
363 if options.profile == 'gmon':
365 ldflags.append('-pg')
366 elif options.profile == 'pprof':
367 cflags.append('-fno-omit-frame-pointer')
368 libs.extend(['-Wl,--no-as-needed', '-lprofiler'])
370 if platform.supports_ppoll() and not options.force_pselect:
371 cflags.append('-DUSE_PPOLL')
372 if platform.supports_ninja_browse():
373 cflags.append('-DNINJA_HAVE_BROWSE')
375 # Search for generated headers relative to build dir.
378 def shell_escape(str):
379 """Escape str such that it's interpreted as a single argument by
382 # This isn't complete, but it's just enough to make NINJA_PYTHON work.
383 if platform.is_windows():
386 return "'%s'" % str.replace("'", "\\'")
389 if 'CFLAGS' in configure_env:
390 cflags.append(configure_env['CFLAGS'])
391 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
392 if 'LDFLAGS' in configure_env:
393 ldflags.append(configure_env['LDFLAGS'])
394 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
397 if platform.is_msvc():
399 command='$cxx $cflags -c $in /Fo$out',
400 description='CXX $out',
401 deps='msvc' # /showIncludes is included in $cflags.
405 command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
408 description='CXX $out')
413 command='lib /nologo /ltcg /out:$out $in',
414 description='LIB $out')
415 elif host.is_mingw():
417 command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
418 description='AR $out')
421 command='rm -f $out && $ar crs $out $in',
422 description='AR $out')
425 if platform.is_msvc():
427 command='$cxx $in $libs /nologo /link $ldflags /out:$out',
428 description='LINK $out')
431 command='$cxx $ldflags -o $out $in $libs',
432 description='LINK $out')
437 if platform.supports_ninja_browse():
438 n.comment('browse_py.h is used to inline browse.py.')
440 command='"%s"' % src('inline.sh') + ' $varname < $in > $out',
441 description='INLINE $out')
442 n.build(built('browse_py.h'), 'inline', src('browse.py'),
443 implicit=src('inline.sh'),
444 variables=[('varname', 'kBrowsePy')])
447 objs += cxx('browse', order_only=built('browse_py.h'))
450 n.comment('the depfile parser and ninja lexers are generated using re2c.')
453 proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
454 return int(proc.communicate()[0], 10) >= 1103
459 command='re2c -b -i --no-generation-date -o $out $in',
460 description='RE2C $out')
461 # Generate the .cc files in the source directory so we can check them in.
462 n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
463 n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
465 print("warning: A compatible version of re2c (>= 0.11.3) was not found; "
466 "changes to src/*.in.cc will not affect your build.")
469 n.comment('Core source files all build into ninja library.')
470 for name in ['build',
489 if platform.is_windows():
490 for name in ['subprocess-win32',
491 'includes_normalize-win32',
493 'msvc_helper_main-win32']:
495 if platform.is_msvc():
496 objs += cxx('minidump-win32')
499 objs += cxx('subprocess-posix')
500 if platform.is_aix():
502 if platform.is_msvc():
503 ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
505 ninja_lib = n.build(built('libninja.a'), 'ar', objs)
508 if platform.is_msvc():
509 libs.append('ninja.lib')
511 libs.append('-lninja')
513 if platform.is_aix():
514 libs.append('-lperfstat')
518 n.comment('Main executable is library plus main() function.')
520 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
521 variables=[('libs', libs)])
525 if options.bootstrap:
526 # We've built the ninja binary. Don't run any more commands
527 # through the bootstrap executor, but continue writing the
531 n.comment('Tests all build into ninja_test executable.')
535 for name in ['build_log_test',
538 'depfile_parser_test',
540 'disk_interface_test',
541 'edit_distance_test',
544 'manifest_parser_test',
551 if platform.is_windows():
552 for name in ['includes_normalize_test', 'msvc_helper_test']:
555 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
556 variables=[('libs', libs)])
558 all_targets += ninja_test
561 n.comment('Ancillary executables.')
562 objs = cxx('build_log_perftest')
563 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
564 implicit=ninja_lib, variables=[('libs', libs)])
565 objs = cxx('canon_perftest')
566 all_targets += n.build(binary('canon_perftest'), 'link', objs,
567 implicit=ninja_lib, variables=[('libs', libs)])
568 objs = cxx('depfile_parser_perftest')
569 all_targets += n.build(binary('depfile_parser_perftest'), 'link', objs,
570 implicit=ninja_lib, variables=[('libs', libs)])
571 objs = cxx('hash_collision_bench')
572 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
573 implicit=ninja_lib, variables=[('libs', libs)])
574 objs = cxx('manifest_parser_perftest')
575 all_targets += n.build(binary('manifest_parser_perftest'), 'link', objs,
576 implicit=ninja_lib, variables=[('libs', libs)])
579 n.comment('Generate a graph using the "graph" tool.')
581 command='./ninja -t graph all > $out')
583 command='dot -Tpng $in > $out')
584 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
585 n.build('graph.png', 'gengraph', dot)
588 n.comment('Generate the manual using asciidoc.')
590 command='asciidoc -b docbook -d book -o $out $in',
591 description='ASCIIDOC $out')
593 command='xsltproc --nonet doc/docbook.xsl $in > $out',
594 description='XSLTPROC $out')
595 xml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
596 manual = n.build(doc('manual.html'), 'xsltproc', xml,
597 implicit=doc('style.css'))
598 n.build('manual', 'phony',
602 n.comment('Generate Doxygen.')
604 command='doxygen $in',
605 description='DOXYGEN $in')
606 n.variable('doxygen_mainpage_generator',
607 src('gen_doxygen_mainpage.sh'))
608 n.rule('doxygen_mainpage',
609 command='$doxygen_mainpage_generator $in > $out',
610 description='DOXYGEN_MAINPAGE $out')
611 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
612 ['README', 'COPYING'],
613 implicit=['$doxygen_mainpage_generator'])
614 n.build('doxygen', 'doxygen', doc('doxygen.config'),
618 if not host.is_mingw():
619 n.comment('Regenerate build files if build script changes.')
621 command='${configure_env}%s $sourcedir/configure.py $configure_args' %
624 n.build('build.ninja', 'configure',
625 implicit=['$sourcedir/configure.py',
626 os.path.normpath('$sourcedir/misc/ninja_syntax.py')])
633 n.comment('Packaging')
635 command="misc/packaging/rpmbuild.sh",
636 description='Building rpms..')
637 n.build('rpm', 'rpmbuild')
640 n.build('all', 'phony', all_targets)
643 print('wrote %s.' % BUILD_FILENAME)
645 if options.bootstrap:
646 print('bootstrap complete. rebuilding...')
650 if platform.can_rebuild_in_place():
651 rebuild_args.append('./ninja')
653 if platform.is_windows():
654 bootstrap_exe = 'ninja.bootstrap.exe'
655 final_exe = 'ninja.exe'
657 bootstrap_exe = './ninja.bootstrap'
658 final_exe = './ninja'
660 if os.path.exists(bootstrap_exe):
661 os.unlink(bootstrap_exe)
662 os.rename(final_exe, bootstrap_exe)
664 rebuild_args.append(bootstrap_exe)
667 rebuild_args.append('-v')
669 subprocess.check_call(rebuild_args)