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('os400'):
64 self._platform = 'os400'
65 elif self._platform.startswith('dragonfly'):
66 self._platform = 'dragonfly'
69 def known_platforms():
70 return ['linux', 'darwin', 'freebsd', 'openbsd', 'solaris', 'sunos5',
71 'mingw', 'msvc', 'gnukfreebsd', 'bitrig', 'netbsd', 'aix',
78 return self._platform == 'linux'
81 return self._platform == 'mingw'
84 return self._platform == 'msvc'
86 def msvc_needs_fs(self):
87 popen = subprocess.Popen(['cl', '/nologo', '/help'],
88 stdout=subprocess.PIPE,
89 stderr=subprocess.PIPE)
90 out, err = popen.communicate()
94 return self.is_mingw() or self.is_msvc()
97 return self._platform == 'solaris'
100 return self._platform == 'aix'
102 def is_os400_pase(self):
103 return self._platform == 'os400' or os.uname().sysname.startswith('OS400')
105 def uses_usr_local(self):
106 return self._platform in ('freebsd', 'openbsd', 'bitrig', 'dragonfly', 'netbsd')
108 def supports_ppoll(self):
109 return self._platform in ('freebsd', 'linux', 'openbsd', 'bitrig',
112 def supports_ninja_browse(self):
113 return (not self.is_windows()
114 and not self.is_solaris()
115 and not self.is_aix())
117 def can_rebuild_in_place(self):
118 return not (self.is_windows() or self.is_aix())
121 """API shim for ninja_syntax.Writer that instead runs the commands.
123 Used to bootstrap Ninja from scratch. In --bootstrap mode this
124 class is used to execute all the commands to build an executable.
125 It also proxies all calls to an underlying ninja_syntax.Writer, to
126 behave like non-bootstrap mode.
128 def __init__(self, writer, verbose=False):
130 self.verbose = verbose
131 # Map of variable name => expanded variable value.
133 # Map of rule name => dict of rule attributes.
138 def comment(self, text):
139 return self.writer.comment(text)
142 return self.writer.newline()
144 def variable(self, key, val):
145 # In bootstrap mode, we have no ninja process to catch /showIncludes
147 self.vars[key] = self._expand(val).replace('/showIncludes', '')
148 return self.writer.variable(key, val)
150 def rule(self, name, **kwargs):
151 self.rules[name] = kwargs
152 return self.writer.rule(name, **kwargs)
154 def build(self, outputs, rule, inputs=None, **kwargs):
155 ruleattr = self.rules[rule]
156 cmd = ruleattr.get('command')
157 if cmd is None: # A phony rule, for example.
160 # Implement just enough of Ninja variable expansion etc. to
161 # make the bootstrap build work.
163 'in': self._expand_paths(inputs),
164 'out': self._expand_paths(outputs)
166 for key, val in kwargs.get('variables', []):
167 local_vars[key] = ' '.join(ninja_syntax.as_list(val))
169 self._run_command(self._expand(cmd, local_vars))
171 return self.writer.build(outputs, rule, inputs, **kwargs)
173 def default(self, paths):
174 return self.writer.default(paths)
176 def _expand_paths(self, paths):
177 """Expand $vars in an array of paths, e.g. from a 'build' block."""
178 paths = ninja_syntax.as_list(paths)
179 return ' '.join(map(self._shell_escape, (map(self._expand, paths))))
181 def _expand(self, str, local_vars={}):
182 """Expand $vars in a string."""
183 return ninja_syntax.expand(str, self.vars, local_vars)
185 def _shell_escape(self, path):
186 """Quote paths containing spaces."""
187 return '"%s"' % path if ' ' in path else path
189 def _run_command(self, cmdline):
190 """Run a subcommand, quietly. Prints the full command on error."""
194 subprocess.check_call(cmdline, shell=True)
195 except subprocess.CalledProcessError:
196 print('when running: ', cmdline)
200 parser = OptionParser()
201 profilers = ['gmon', 'pprof']
202 parser.add_option('--bootstrap', action='store_true',
203 help='bootstrap a ninja binary from nothing')
204 parser.add_option('--verbose', action='store_true',
205 help='enable verbose build')
206 parser.add_option('--platform',
207 help='target platform (' +
208 '/'.join(Platform.known_platforms()) + ')',
209 choices=Platform.known_platforms())
210 parser.add_option('--host',
211 help='host platform (' +
212 '/'.join(Platform.known_platforms()) + ')',
213 choices=Platform.known_platforms())
214 parser.add_option('--debug', action='store_true',
215 help='enable debugging extras',)
216 parser.add_option('--profile', metavar='TYPE',
218 help='enable profiling (' + '/'.join(profilers) + ')',)
219 parser.add_option('--with-gtest', metavar='PATH', help='ignored')
220 parser.add_option('--with-python', metavar='EXE',
221 help='use EXE as the Python interpreter',
222 default=os.path.basename(sys.executable))
223 parser.add_option('--force-pselect', action='store_true',
224 help='ppoll() is used by default where available, '
225 'but some platforms may need to use pselect instead',)
226 (options, args) = parser.parse_args()
228 print('ERROR: extra unparsed command-line arguments:', args)
231 platform = Platform(options.platform)
233 host = Platform(options.host)
237 BUILD_FILENAME = 'build.ninja'
238 ninja_writer = ninja_syntax.Writer(open(BUILD_FILENAME, 'w'))
241 if options.bootstrap:
242 # Make the build directory.
247 # Wrap ninja_writer with the Bootstrapper, which also executes the
249 print('bootstrapping ninja...')
250 n = Bootstrap(n, verbose=options.verbose)
252 n.comment('This file is used to build ninja itself.')
253 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
256 n.variable('ninja_required_version', '1.3')
259 n.comment('The arguments passed to configure.py, for rerunning it.')
260 configure_args = sys.argv[1:]
261 if '--bootstrap' in configure_args:
262 configure_args.remove('--bootstrap')
263 n.variable('configure_args', ' '.join(configure_args))
264 env_keys = set(['CXX', 'AR', 'CFLAGS', 'CXXFLAGS', 'LDFLAGS'])
265 configure_env = dict((k, os.environ[k]) for k in os.environ if k in env_keys)
267 config_str = ' '.join([k + '=' + pipes.quote(configure_env[k])
268 for k in configure_env])
269 n.variable('configure_env', config_str + '$ ')
272 CXX = configure_env.get('CXX', 'c++')
274 if platform.is_msvc():
279 return os.path.join('$root', 'src', filename)
281 return os.path.join('$builddir', filename)
283 return os.path.join('$root', 'doc', filename)
284 def cc(name, **kwargs):
285 return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
286 def cxx(name, **kwargs):
287 return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
289 if platform.is_windows():
291 n.build(name, 'phony', exe)
296 if root == os.getcwd():
297 # In the common case where we're building directly in the source
298 # tree, simplify all the paths to just be cwd-relative.
300 n.variable('root', root)
301 n.variable('builddir', 'build')
302 n.variable('cxx', CXX)
303 if platform.is_msvc():
304 n.variable('ar', 'link')
306 n.variable('ar', configure_env.get('AR', 'ar'))
308 if platform.is_msvc():
309 cflags = ['/showIncludes',
310 '/nologo', # Don't print startup banner.
311 '/Zi', # Create pdb with debug info.
312 '/W4', # Highest warning level.
313 '/WX', # Warnings as errors.
314 '/wd4530', '/wd4100', '/wd4706', '/wd4244',
315 '/wd4512', '/wd4800', '/wd4702', '/wd4819',
316 # Disable warnings about constant conditional expressions.
318 # Disable warnings about passing "this" during initialization.
320 # Disable warnings about ignored typedef in DbgHelp.h
322 '/GR-', # Disable RTTI.
323 # Disable size_t -> int truncation warning.
324 # We never have strings or arrays larger than 2**31.
326 '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
327 '/D_HAS_EXCEPTIONS=0',
328 '/DNINJA_PYTHON="%s"' % options.with_python]
329 if platform.msvc_needs_fs():
331 ldflags = ['/DEBUG', '/libpath:$builddir']
332 if not options.debug:
333 cflags += ['/Ox', '/DNDEBUG', '/GL']
334 ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
336 cflags = ['-g', '-Wall', '-Wextra',
338 '-Wno-missing-field-initializers',
339 '-Wno-unused-parameter',
342 '-fvisibility=hidden', '-pipe',
343 '-DNINJA_PYTHON="%s"' % options.with_python]
345 cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
346 cflags.remove('-fno-rtti') # Needed for above pedanticness.
348 cflags += ['-O2', '-DNDEBUG']
350 proc = subprocess.Popen(
351 [CXX, '-fdiagnostics-color', '-c', '-x', 'c++', '/dev/null',
353 stdout=open(os.devnull, 'wb'), stderr=subprocess.STDOUT)
355 cflags += ['-fdiagnostics-color']
358 if platform.is_mingw():
359 cflags += ['-D_WIN32_WINNT=0x0601', '-D__USE_MINGW_ANSI_STDIO=1']
360 ldflags = ['-L$builddir']
361 if platform.uses_usr_local():
362 cflags.append('-I/usr/local/include')
363 ldflags.append('-L/usr/local/lib')
364 if platform.is_aix():
365 # printf formats for int64_t, uint64_t; large file support
366 cflags.append('-D__STDC_FORMAT_MACROS')
367 cflags.append('-D_LARGE_FILES')
372 if platform.is_mingw():
373 cflags.remove('-fvisibility=hidden');
374 ldflags.append('-static')
375 elif platform.is_solaris():
376 cflags.remove('-fvisibility=hidden')
377 elif platform.is_aix():
378 cflags.remove('-fvisibility=hidden')
379 elif platform.is_msvc():
382 if options.profile == 'gmon':
384 ldflags.append('-pg')
385 elif options.profile == 'pprof':
386 cflags.append('-fno-omit-frame-pointer')
387 libs.extend(['-Wl,--no-as-needed', '-lprofiler'])
389 if platform.supports_ppoll() and not options.force_pselect:
390 cflags.append('-DUSE_PPOLL')
391 if platform.supports_ninja_browse():
392 cflags.append('-DNINJA_HAVE_BROWSE')
394 # Search for generated headers relative to build dir.
397 def shell_escape(str):
398 """Escape str such that it's interpreted as a single argument by
401 # This isn't complete, but it's just enough to make NINJA_PYTHON work.
402 if platform.is_windows():
405 return "'%s'" % str.replace("'", "\\'")
408 if 'CFLAGS' in configure_env:
409 cflags.append(configure_env['CFLAGS'])
410 ldflags.append(configure_env['CFLAGS'])
411 if 'CXXFLAGS' in configure_env:
412 cflags.append(configure_env['CXXFLAGS'])
413 ldflags.append(configure_env['CXXFLAGS'])
414 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
415 if 'LDFLAGS' in configure_env:
416 ldflags.append(configure_env['LDFLAGS'])
417 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
420 if platform.is_msvc():
422 command='$cxx $cflags -c $in /Fo$out /Fd' + built('$pdb'),
423 description='CXX $out',
424 deps='msvc' # /showIncludes is included in $cflags.
428 command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
431 description='CXX $out')
436 command='lib /nologo /ltcg /out:$out $in',
437 description='LIB $out')
438 elif host.is_mingw():
440 command='$ar crs $out $in',
441 description='AR $out')
444 command='rm -f $out && $ar crs $out $in',
445 description='AR $out')
448 if platform.is_msvc():
450 command='$cxx $in $libs /nologo /link $ldflags /out:$out',
451 description='LINK $out')
454 command='$cxx $ldflags -o $out $in $libs',
455 description='LINK $out')
460 if platform.supports_ninja_browse():
461 n.comment('browse_py.h is used to inline browse.py.')
463 command='"%s"' % src('inline.sh') + ' $varname < $in > $out',
464 description='INLINE $out')
465 n.build(built('browse_py.h'), 'inline', src('browse.py'),
466 implicit=src('inline.sh'),
467 variables=[('varname', 'kBrowsePy')])
470 objs += cxx('browse', order_only=built('browse_py.h'))
473 n.comment('the depfile parser and ninja lexers are generated using re2c.')
476 proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
477 return int(proc.communicate()[0], 10) >= 1103
482 command='re2c -b -i --no-generation-date --no-version -o $out $in',
483 description='RE2C $out')
484 # Generate the .cc files in the source directory so we can check them in.
485 n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
486 n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
488 print("warning: A compatible version of re2c (>= 0.11.3) was not found; "
489 "changes to src/*.in.cc will not affect your build.")
492 n.comment('Core source files all build into ninja library.')
494 if platform.is_msvc():
495 cxxvariables = [('pdb', 'ninja.pdb')]
496 for name in ['build',
522 objs += cxx(name, variables=cxxvariables)
523 if platform.is_windows():
524 for name in ['subprocess-win32',
525 'includes_normalize-win32',
527 'msvc_helper_main-win32']:
528 objs += cxx(name, variables=cxxvariables)
529 if platform.is_msvc():
530 objs += cxx('minidump-win32', variables=cxxvariables)
533 objs += cxx('subprocess-posix')
534 if platform.is_aix():
536 if platform.is_msvc():
537 ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
539 ninja_lib = n.build(built('libninja.a'), 'ar', objs)
542 if platform.is_msvc():
543 libs.append('ninja.lib')
545 libs.append('-lninja')
547 if platform.is_aix() and not platform.is_os400_pase():
548 libs.append('-lperfstat')
552 n.comment('Main executable is library plus main() function.')
553 objs = cxx('ninja', variables=cxxvariables)
554 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
555 variables=[('libs', libs)])
559 if options.bootstrap:
560 # We've built the ninja binary. Don't run any more commands
561 # through the bootstrap executor, but continue writing the
565 n.comment('Tests all build into ninja_test executable.')
568 if platform.is_msvc():
569 cxxvariables = [('pdb', 'ninja_test.pdb')]
571 for name in ['build_log_test',
575 'depfile_parser_test',
577 'dyndep_parser_test',
578 'disk_interface_test',
579 'edit_distance_test',
583 'manifest_parser_test',
588 'string_piece_util_test',
592 objs += cxx(name, variables=cxxvariables)
593 if platform.is_windows():
594 for name in ['includes_normalize_test', 'msvc_helper_test']:
595 objs += cxx(name, variables=cxxvariables)
597 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
598 variables=[('libs', libs)])
600 all_targets += ninja_test
603 n.comment('Ancillary executables.')
605 if platform.is_aix() and '-maix64' not in ldflags:
606 # Both hash_collision_bench and manifest_parser_perftest require more
607 # memory than will fit in the standard 32-bit AIX shared stack/heap (256M)
608 libs.append('-Wl,-bmaxdata:0x80000000')
610 for name in ['build_log_perftest',
612 'depfile_parser_perftest',
613 'hash_collision_bench',
614 'manifest_parser_perftest',
615 'clparser_perftest']:
616 if platform.is_msvc():
617 cxxvariables = [('pdb', name + '.pdb')]
618 objs = cxx(name, variables=cxxvariables)
619 all_targets += n.build(binary(name), 'link', objs,
620 implicit=ninja_lib, variables=[('libs', libs)])
624 n.comment('Generate a graph using the "graph" tool.')
626 command='./ninja -t graph all > $out')
628 command='dot -Tpng $in > $out')
629 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
630 n.build('graph.png', 'gengraph', dot)
633 n.comment('Generate the manual using asciidoc.')
635 command='asciidoc -b docbook -d book -o $out $in',
636 description='ASCIIDOC $out')
638 command='xsltproc --nonet doc/docbook.xsl $in > $out',
639 description='XSLTPROC $out')
640 docbookxml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
641 manual = n.build(doc('manual.html'), 'xsltproc', docbookxml,
642 implicit=[doc('style.css'), doc('docbook.xsl')])
643 n.build('manual', 'phony',
648 command='dblatex -q -o $out -p doc/dblatex.xsl $in',
649 description='DBLATEX $out')
650 n.build(doc('manual.pdf'), 'dblatex', docbookxml,
651 implicit=[doc('dblatex.xsl')])
653 n.comment('Generate Doxygen.')
655 command='doxygen $in',
656 description='DOXYGEN $in')
657 n.variable('doxygen_mainpage_generator',
658 src('gen_doxygen_mainpage.sh'))
659 n.rule('doxygen_mainpage',
660 command='$doxygen_mainpage_generator $in > $out',
661 description='DOXYGEN_MAINPAGE $out')
662 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
663 ['README.md', 'COPYING'],
664 implicit=['$doxygen_mainpage_generator'])
665 n.build('doxygen', 'doxygen', doc('doxygen.config'),
669 if not host.is_mingw():
670 n.comment('Regenerate build files if build script changes.')
672 command='${configure_env}%s $root/configure.py $configure_args' %
675 n.build('build.ninja', 'configure',
676 implicit=['$root/configure.py',
677 os.path.normpath('$root/misc/ninja_syntax.py')])
684 n.comment('Packaging')
686 command="misc/packaging/rpmbuild.sh",
687 description='Building rpms..')
688 n.build('rpm', 'rpmbuild')
691 n.build('all', 'phony', all_targets)
694 print('wrote %s.' % BUILD_FILENAME)
696 if options.bootstrap:
697 print('bootstrap complete. rebuilding...')
701 if platform.can_rebuild_in_place():
702 rebuild_args.append('./ninja')
704 if platform.is_windows():
705 bootstrap_exe = 'ninja.bootstrap.exe'
706 final_exe = 'ninja.exe'
708 bootstrap_exe = './ninja.bootstrap'
709 final_exe = './ninja'
711 if os.path.exists(bootstrap_exe):
712 os.unlink(bootstrap_exe)
713 os.rename(final_exe, bootstrap_exe)
715 rebuild_args.append(bootstrap_exe)
718 rebuild_args.append('-v')
720 subprocess.check_call(rebuild_args)