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'
63 elif self._platform.startswith('dragonfly'):
64 self._platform = 'dragonfly'
67 def known_platforms():
68 return ['linux', 'darwin', 'freebsd', 'openbsd', 'solaris', 'sunos5',
69 'mingw', 'msvc', 'gnukfreebsd', 'bitrig', 'netbsd', 'aix',
76 return self._platform == 'linux'
79 return self._platform == 'mingw'
82 return self._platform == 'msvc'
84 def msvc_needs_fs(self):
85 popen = subprocess.Popen(['cl', '/nologo', '/?'],
86 stdout=subprocess.PIPE,
87 stderr=subprocess.PIPE)
88 out, err = popen.communicate()
92 return self.is_mingw() or self.is_msvc()
95 return self._platform == 'solaris'
98 return self._platform == 'aix'
100 def uses_usr_local(self):
101 return self._platform in ('freebsd', 'openbsd', 'bitrig', 'dragonfly', 'netbsd')
103 def supports_ppoll(self):
104 return self._platform in ('freebsd', 'linux', 'openbsd', 'bitrig',
107 def supports_ninja_browse(self):
108 return (not self.is_windows()
109 and not self.is_solaris()
110 and not self.is_aix())
112 def can_rebuild_in_place(self):
113 return not (self.is_windows() or self.is_aix())
116 """API shim for ninja_syntax.Writer that instead runs the commands.
118 Used to bootstrap Ninja from scratch. In --bootstrap mode this
119 class is used to execute all the commands to build an executable.
120 It also proxies all calls to an underlying ninja_syntax.Writer, to
121 behave like non-bootstrap mode.
123 def __init__(self, writer, verbose=False):
125 self.verbose = verbose
126 # Map of variable name => expanded variable value.
128 # Map of rule name => dict of rule attributes.
133 def comment(self, text):
134 return self.writer.comment(text)
137 return self.writer.newline()
139 def variable(self, key, val):
140 # In bootstrap mode, we have no ninja process to catch /showIncludes
142 self.vars[key] = self._expand(val).replace('/showIncludes', '')
143 return self.writer.variable(key, val)
145 def rule(self, name, **kwargs):
146 self.rules[name] = kwargs
147 return self.writer.rule(name, **kwargs)
149 def build(self, outputs, rule, inputs=None, **kwargs):
150 ruleattr = self.rules[rule]
151 cmd = ruleattr.get('command')
152 if cmd is None: # A phony rule, for example.
155 # Implement just enough of Ninja variable expansion etc. to
156 # make the bootstrap build work.
158 'in': self._expand_paths(inputs),
159 'out': self._expand_paths(outputs)
161 for key, val in kwargs.get('variables', []):
162 local_vars[key] = ' '.join(ninja_syntax.as_list(val))
164 self._run_command(self._expand(cmd, local_vars))
166 return self.writer.build(outputs, rule, inputs, **kwargs)
168 def default(self, paths):
169 return self.writer.default(paths)
171 def _expand_paths(self, paths):
172 """Expand $vars in an array of paths, e.g. from a 'build' block."""
173 paths = ninja_syntax.as_list(paths)
174 return ' '.join(map(self._shell_escape, (map(self._expand, paths))))
176 def _expand(self, str, local_vars={}):
177 """Expand $vars in a string."""
178 return ninja_syntax.expand(str, self.vars, local_vars)
180 def _shell_escape(self, path):
181 """Quote paths containing spaces."""
182 return '"%s"' % path if ' ' in path else path
184 def _run_command(self, cmdline):
185 """Run a subcommand, quietly. Prints the full command on error."""
189 subprocess.check_call(cmdline, shell=True)
190 except subprocess.CalledProcessError:
191 print('when running: ', cmdline)
195 parser = OptionParser()
196 profilers = ['gmon', 'pprof']
197 parser.add_option('--bootstrap', action='store_true',
198 help='bootstrap a ninja binary from nothing')
199 parser.add_option('--verbose', action='store_true',
200 help='enable verbose build')
201 parser.add_option('--platform',
202 help='target platform (' +
203 '/'.join(Platform.known_platforms()) + ')',
204 choices=Platform.known_platforms())
205 parser.add_option('--host',
206 help='host platform (' +
207 '/'.join(Platform.known_platforms()) + ')',
208 choices=Platform.known_platforms())
209 parser.add_option('--debug', action='store_true',
210 help='enable debugging extras',)
211 parser.add_option('--profile', metavar='TYPE',
213 help='enable profiling (' + '/'.join(profilers) + ')',)
214 parser.add_option('--with-gtest', metavar='PATH', help='ignored')
215 parser.add_option('--with-python', metavar='EXE',
216 help='use EXE as the Python interpreter',
217 default=os.path.basename(sys.executable))
218 parser.add_option('--force-pselect', action='store_true',
219 help='ppoll() is used by default where available, '
220 'but some platforms may need to use pselect instead',)
221 (options, args) = parser.parse_args()
223 print('ERROR: extra unparsed command-line arguments:', args)
226 platform = Platform(options.platform)
228 host = Platform(options.host)
232 BUILD_FILENAME = 'build.ninja'
233 ninja_writer = ninja_syntax.Writer(open(BUILD_FILENAME, 'w'))
236 if options.bootstrap:
237 # Make the build directory.
242 # Wrap ninja_writer with the Bootstrapper, which also executes the
244 print('bootstrapping ninja...')
245 n = Bootstrap(n, verbose=options.verbose)
247 n.comment('This file is used to build ninja itself.')
248 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
251 n.variable('ninja_required_version', '1.3')
254 n.comment('The arguments passed to configure.py, for rerunning it.')
255 configure_args = sys.argv[1:]
256 if '--bootstrap' in configure_args:
257 configure_args.remove('--bootstrap')
258 n.variable('configure_args', ' '.join(configure_args))
259 env_keys = set(['CXX', 'AR', 'CFLAGS', 'CXXFLAGS', 'LDFLAGS'])
260 configure_env = dict((k, os.environ[k]) for k in os.environ if k in env_keys)
262 config_str = ' '.join([k + '=' + pipes.quote(configure_env[k])
263 for k in configure_env])
264 n.variable('configure_env', config_str + '$ ')
267 CXX = configure_env.get('CXX', 'g++')
269 if platform.is_msvc():
274 return os.path.join('$root', 'src', filename)
276 return os.path.join('$builddir', filename)
278 return os.path.join('$root', 'doc', filename)
279 def cc(name, **kwargs):
280 return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
281 def cxx(name, **kwargs):
282 return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
284 if platform.is_windows():
286 n.build(name, 'phony', exe)
291 if root == os.getcwd():
292 # In the common case where we're building directly in the source
293 # tree, simplify all the paths to just be cwd-relative.
295 n.variable('root', root)
296 n.variable('builddir', 'build')
297 n.variable('cxx', CXX)
298 if platform.is_msvc():
299 n.variable('ar', 'link')
301 n.variable('ar', configure_env.get('AR', 'ar'))
303 if platform.is_msvc():
304 cflags = ['/showIncludes',
305 '/nologo', # Don't print startup banner.
306 '/Zi', # Create pdb with debug info.
307 '/W4', # Highest warning level.
308 '/WX', # Warnings as errors.
309 '/wd4530', '/wd4100', '/wd4706', '/wd4244',
310 '/wd4512', '/wd4800', '/wd4702', '/wd4819',
311 # Disable warnings about constant conditional expressions.
313 # Disable warnings about passing "this" during initialization.
315 # Disable warnings about ignored typedef in DbgHelp.h
317 '/GR-', # Disable RTTI.
318 # Disable size_t -> int truncation warning.
319 # We never have strings or arrays larger than 2**31.
321 '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
322 '/D_HAS_EXCEPTIONS=0',
323 '/DNINJA_PYTHON="%s"' % options.with_python]
324 if platform.msvc_needs_fs():
326 ldflags = ['/DEBUG', '/libpath:$builddir']
327 if not options.debug:
328 cflags += ['/Ox', '/DNDEBUG', '/GL']
329 ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
331 cflags = ['-g', '-Wall', '-Wextra',
333 '-Wno-missing-field-initializers',
334 '-Wno-unused-parameter',
337 '-fvisibility=hidden', '-pipe',
338 '-DNINJA_PYTHON="%s"' % options.with_python]
340 cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
341 cflags.remove('-fno-rtti') # Needed for above pedanticness.
343 cflags += ['-O2', '-DNDEBUG']
345 proc = subprocess.Popen(
346 [CXX, '-fdiagnostics-color', '-c', '-x', 'c++', '/dev/null',
348 stdout=open(os.devnull, 'wb'), stderr=subprocess.STDOUT)
350 cflags += ['-fdiagnostics-color']
353 if platform.is_mingw():
354 cflags += ['-D_WIN32_WINNT=0x0501']
355 ldflags = ['-L$builddir']
356 if platform.uses_usr_local():
357 cflags.append('-I/usr/local/include')
358 ldflags.append('-L/usr/local/lib')
359 if platform.is_aix():
360 # printf formats for int64_t, uint64_t; large file support
361 cflags.append('-D__STDC_FORMAT_MACROS')
362 cflags.append('-D_LARGE_FILES')
367 if platform.is_mingw():
368 cflags.remove('-fvisibility=hidden');
369 ldflags.append('-static')
370 elif platform.is_solaris():
371 cflags.remove('-fvisibility=hidden')
372 elif platform.is_aix():
373 cflags.remove('-fvisibility=hidden')
374 elif platform.is_msvc():
377 if options.profile == 'gmon':
379 ldflags.append('-pg')
380 elif options.profile == 'pprof':
381 cflags.append('-fno-omit-frame-pointer')
382 libs.extend(['-Wl,--no-as-needed', '-lprofiler'])
384 if platform.supports_ppoll() and not options.force_pselect:
385 cflags.append('-DUSE_PPOLL')
386 if platform.supports_ninja_browse():
387 cflags.append('-DNINJA_HAVE_BROWSE')
389 # Search for generated headers relative to build dir.
392 def shell_escape(str):
393 """Escape str such that it's interpreted as a single argument by
396 # This isn't complete, but it's just enough to make NINJA_PYTHON work.
397 if platform.is_windows():
400 return "'%s'" % str.replace("'", "\\'")
403 if 'CFLAGS' in configure_env:
404 cflags.append(configure_env['CFLAGS'])
405 ldflags.append(configure_env['CFLAGS'])
406 if 'CXXFLAGS' in configure_env:
407 cflags.append(configure_env['CXXFLAGS'])
408 ldflags.append(configure_env['CXXFLAGS'])
409 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
410 if 'LDFLAGS' in configure_env:
411 ldflags.append(configure_env['LDFLAGS'])
412 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
415 if platform.is_msvc():
417 command='$cxx $cflags -c $in /Fo$out /Fd' + built('$pdb'),
418 description='CXX $out',
419 deps='msvc' # /showIncludes is included in $cflags.
423 command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
426 description='CXX $out')
431 command='lib /nologo /ltcg /out:$out $in',
432 description='LIB $out')
433 elif host.is_mingw():
435 command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
436 description='AR $out')
439 command='rm -f $out && $ar crs $out $in',
440 description='AR $out')
443 if platform.is_msvc():
445 command='$cxx $in $libs /nologo /link $ldflags /out:$out',
446 description='LINK $out')
449 command='$cxx $ldflags -o $out $in $libs',
450 description='LINK $out')
455 if platform.supports_ninja_browse():
456 n.comment('browse_py.h is used to inline browse.py.')
458 command='"%s"' % src('inline.sh') + ' $varname < $in > $out',
459 description='INLINE $out')
460 n.build(built('browse_py.h'), 'inline', src('browse.py'),
461 implicit=src('inline.sh'),
462 variables=[('varname', 'kBrowsePy')])
465 objs += cxx('browse', order_only=built('browse_py.h'))
468 n.comment('the depfile parser and ninja lexers are generated using re2c.')
471 proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
472 return int(proc.communicate()[0], 10) >= 1103
477 command='re2c -b -i --no-generation-date -o $out $in',
478 description='RE2C $out')
479 # Generate the .cc files in the source directory so we can check them in.
480 n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
481 n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
483 print("warning: A compatible version of re2c (>= 0.11.3) was not found; "
484 "changes to src/*.in.cc will not affect your build.")
487 n.comment('Core source files all build into ninja library.')
489 if platform.is_msvc():
490 cxxvariables = [('pdb', 'ninja.pdb')]
491 for name in ['build',
511 objs += cxx(name, variables=cxxvariables)
512 if platform.is_windows():
513 for name in ['subprocess-win32',
514 'includes_normalize-win32',
516 'msvc_helper_main-win32']:
517 objs += cxx(name, variables=cxxvariables)
518 if platform.is_msvc():
519 objs += cxx('minidump-win32', variables=cxxvariables)
522 objs += cxx('subprocess-posix')
523 if platform.is_aix():
525 if platform.is_msvc():
526 ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
528 ninja_lib = n.build(built('libninja.a'), 'ar', objs)
531 if platform.is_msvc():
532 libs.append('ninja.lib')
534 libs.append('-lninja')
536 if platform.is_aix():
537 libs.append('-lperfstat')
541 n.comment('Main executable is library plus main() function.')
542 objs = cxx('ninja', variables=cxxvariables)
543 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
544 variables=[('libs', libs)])
548 if options.bootstrap:
549 # We've built the ninja binary. Don't run any more commands
550 # through the bootstrap executor, but continue writing the
554 n.comment('Tests all build into ninja_test executable.')
557 if platform.is_msvc():
558 cxxvariables = [('pdb', 'ninja_test.pdb')]
560 for name in ['build_log_test',
564 'depfile_parser_test',
566 'disk_interface_test',
567 'edit_distance_test',
570 'manifest_parser_test',
573 'string_piece_util_test',
577 objs += cxx(name, variables=cxxvariables)
578 if platform.is_windows():
579 for name in ['includes_normalize_test', 'msvc_helper_test']:
580 objs += cxx(name, variables=cxxvariables)
582 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
583 variables=[('libs', libs)])
585 all_targets += ninja_test
588 n.comment('Ancillary executables.')
590 for name in ['build_log_perftest',
592 'depfile_parser_perftest',
593 'hash_collision_bench',
594 'manifest_parser_perftest',
595 'clparser_perftest']:
596 if platform.is_msvc():
597 cxxvariables = [('pdb', name + '.pdb')]
598 objs = cxx(name, variables=cxxvariables)
599 all_targets += n.build(binary(name), 'link', objs,
600 implicit=ninja_lib, variables=[('libs', libs)])
604 n.comment('Generate a graph using the "graph" tool.')
606 command='./ninja -t graph all > $out')
608 command='dot -Tpng $in > $out')
609 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
610 n.build('graph.png', 'gengraph', dot)
613 n.comment('Generate the manual using asciidoc.')
615 command='asciidoc -b docbook -d book -o $out $in',
616 description='ASCIIDOC $out')
618 command='xsltproc --nonet doc/docbook.xsl $in > $out',
619 description='XSLTPROC $out')
620 docbookxml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
621 manual = n.build(doc('manual.html'), 'xsltproc', docbookxml,
622 implicit=[doc('style.css'), doc('docbook.xsl')])
623 n.build('manual', 'phony',
628 command='dblatex -q -o $out -p doc/dblatex.xsl $in',
629 description='DBLATEX $out')
630 n.build(doc('manual.pdf'), 'dblatex', docbookxml,
631 implicit=[doc('dblatex.xsl')])
633 n.comment('Generate Doxygen.')
635 command='doxygen $in',
636 description='DOXYGEN $in')
637 n.variable('doxygen_mainpage_generator',
638 src('gen_doxygen_mainpage.sh'))
639 n.rule('doxygen_mainpage',
640 command='$doxygen_mainpage_generator $in > $out',
641 description='DOXYGEN_MAINPAGE $out')
642 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
643 ['README', 'COPYING'],
644 implicit=['$doxygen_mainpage_generator'])
645 n.build('doxygen', 'doxygen', doc('doxygen.config'),
649 if not host.is_mingw():
650 n.comment('Regenerate build files if build script changes.')
652 command='${configure_env}%s $root/configure.py $configure_args' %
655 n.build('build.ninja', 'configure',
656 implicit=['$root/configure.py',
657 os.path.normpath('$root/misc/ninja_syntax.py')])
664 n.comment('Packaging')
666 command="misc/packaging/rpmbuild.sh",
667 description='Building rpms..')
668 n.build('rpm', 'rpmbuild')
671 n.build('all', 'phony', all_targets)
674 print('wrote %s.' % BUILD_FILENAME)
676 if options.bootstrap:
677 print('bootstrap complete. rebuilding...')
681 if platform.can_rebuild_in_place():
682 rebuild_args.append('./ninja')
684 if platform.is_windows():
685 bootstrap_exe = 'ninja.bootstrap.exe'
686 final_exe = 'ninja.exe'
688 bootstrap_exe = './ninja.bootstrap'
689 final_exe = './ninja'
691 if os.path.exists(bootstrap_exe):
692 os.unlink(bootstrap_exe)
693 os.rename(final_exe, bootstrap_exe)
695 rebuild_args.append(bootstrap_exe)
698 rebuild_args.append('-v')
700 subprocess.check_call(rebuild_args)