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 sys.path.insert(0, 'misc')
35 class Platform(object):
36 """Represents a host/target platform and its specific build attributes."""
37 def __init__(self, platform):
38 self._platform = platform
39 if self._platform is not None:
41 self._platform = sys.platform
42 if self._platform.startswith('linux'):
43 self._platform = 'linux'
44 elif self._platform.startswith('freebsd'):
45 self._platform = 'freebsd'
46 elif self._platform.startswith('gnukfreebsd'):
47 self._platform = 'freebsd'
48 elif self._platform.startswith('openbsd'):
49 self._platform = 'openbsd'
50 elif self._platform.startswith('solaris') or self._platform == 'sunos5':
51 self._platform = 'solaris'
52 elif self._platform.startswith('mingw'):
53 self._platform = 'mingw'
54 elif self._platform.startswith('win'):
55 self._platform = 'msvc'
56 elif self._platform.startswith('bitrig'):
57 self._platform = 'bitrig'
58 elif self._platform.startswith('netbsd'):
59 self._platform = 'netbsd'
62 def known_platforms():
63 return ['linux', 'darwin', 'freebsd', 'openbsd', 'solaris', 'sunos5',
64 'mingw', 'msvc', 'gnukfreebsd', 'bitrig', 'netbsd']
70 return self._platform == 'linux'
73 return self._platform == 'mingw'
76 return self._platform == 'msvc'
78 def msvc_needs_fs(self):
79 popen = subprocess.Popen(['cl', '/nologo', '/?'],
80 stdout=subprocess.PIPE,
81 stderr=subprocess.PIPE)
82 out, err = popen.communicate()
83 return '/FS ' in str(out)
86 return self.is_mingw() or self.is_msvc()
89 return self._platform == 'solaris'
91 def uses_usr_local(self):
92 return self._platform in ('freebsd', 'openbsd', 'bitrig')
94 def supports_ppoll(self):
95 return self._platform in ('linux', 'openbsd', 'bitrig')
97 def supports_ninja_browse(self):
98 return not self.is_windows() and not self.is_solaris()
102 """API shim for ninja_syntax.Writer that instead runs the commands.
104 Used to bootstrap Ninja from scratch. In --bootstrap mode this
105 class is used to execute all the commands to build an executable.
106 It also proxies all calls to an underlying ninja_syntax.Writer, to
107 behave like non-bootstrap mode.
109 def __init__(self, writer):
111 # Map of variable name => expanded variable value.
113 # Map of rule name => dict of rule attributes.
118 def comment(self, text):
119 return self.writer.comment(text)
122 return self.writer.newline()
124 def variable(self, key, val):
125 self.vars[key] = self._expand(val)
126 return self.writer.variable(key, val)
128 def rule(self, name, **kwargs):
129 self.rules[name] = kwargs
130 return self.writer.rule(name, **kwargs)
132 def build(self, outputs, rule, inputs=None, **kwargs):
133 ruleattr = self.rules[rule]
134 cmd = ruleattr.get('command')
135 if cmd is None: # A phony rule, for example.
138 # Implement just enough of Ninja variable expansion etc. to
139 # make the bootstrap build work.
141 'in': self._expand_paths(inputs),
142 'out': self._expand_paths(outputs)
144 for key, val in kwargs.get('variables', []):
145 local_vars[key] = ' '.join(ninja_syntax.as_list(val))
147 self._run_command(self._expand(cmd, local_vars))
149 return self.writer.build(outputs, rule, inputs, **kwargs)
151 def default(self, paths):
152 return self.writer.default(paths)
154 def _expand_paths(self, paths):
155 """Expand $vars in an array of paths, e.g. from a 'build' block."""
156 paths = ninja_syntax.as_list(paths)
157 return ' '.join(map(self._expand, paths))
159 def _expand(self, str, local_vars={}):
160 """Expand $vars in a string."""
161 return ninja_syntax.expand(str, self.vars, local_vars)
163 def _run_command(self, cmdline):
164 """Run a subcommand, quietly. Prints the full command on error."""
166 subprocess.check_call(cmdline, shell=True)
167 except subprocess.CalledProcessError:
168 print('when running: ', cmdline)
172 parser = OptionParser()
173 profilers = ['gmon', 'pprof']
174 parser.add_option('--bootstrap', action='store_true',
175 help='bootstrap a ninja binary from nothing')
176 parser.add_option('--platform',
177 help='target platform (' +
178 '/'.join(Platform.known_platforms()) + ')',
179 choices=Platform.known_platforms())
180 parser.add_option('--host',
181 help='host platform (' +
182 '/'.join(Platform.known_platforms()) + ')',
183 choices=Platform.known_platforms())
184 parser.add_option('--debug', action='store_true',
185 help='enable debugging extras',)
186 parser.add_option('--profile', metavar='TYPE',
188 help='enable profiling (' + '/'.join(profilers) + ')',)
189 parser.add_option('--with-gtest', metavar='PATH', help='ignored')
190 parser.add_option('--with-python', metavar='EXE',
191 help='use EXE as the Python interpreter',
192 default=os.path.basename(sys.executable))
193 parser.add_option('--force-pselect', action='store_true',
194 help='ppoll() is used by default where available, '
195 'but some platforms may need to use pselect instead',)
196 (options, args) = parser.parse_args()
198 print('ERROR: extra unparsed command-line arguments:', args)
201 platform = Platform(options.platform)
203 host = Platform(options.host)
207 BUILD_FILENAME = 'build.ninja'
208 ninja_writer = ninja_syntax.Writer(open(BUILD_FILENAME, 'w'))
211 if options.bootstrap:
212 # Make the build directory.
217 # Wrap ninja_writer with the Bootstrapper, which also executes the
219 print('bootstrapping ninja...')
222 n.comment('This file is used to build ninja itself.')
223 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
226 n.variable('ninja_required_version', '1.3')
229 n.comment('The arguments passed to configure.py, for rerunning it.')
230 configure_args = sys.argv[1:]
231 if '--bootstrap' in configure_args:
232 configure_args.remove('--bootstrap')
233 n.variable('configure_args', ' '.join(configure_args))
234 env_keys = set(['CXX', 'AR', 'CFLAGS', 'LDFLAGS'])
235 configure_env = dict((k, os.environ[k]) for k in os.environ if k in env_keys)
237 config_str = ' '.join([k + '=' + pipes.quote(configure_env[k])
238 for k in configure_env])
239 n.variable('configure_env', config_str + '$ ')
242 CXX = configure_env.get('CXX', 'g++')
244 if platform.is_msvc():
249 return os.path.join('src', filename)
251 return os.path.join('$builddir', filename)
253 return os.path.join('doc', filename)
254 def cc(name, **kwargs):
255 return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
256 def cxx(name, **kwargs):
257 return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
259 if platform.is_windows():
261 n.build(name, 'phony', exe)
265 n.variable('builddir', 'build')
266 n.variable('cxx', CXX)
267 if platform.is_msvc():
268 n.variable('ar', 'link')
270 n.variable('ar', configure_env.get('AR', 'ar'))
272 if platform.is_msvc():
273 cflags = ['/showIncludes',
274 '/nologo', # Don't print startup banner.
275 '/Zi', # Create pdb with debug info.
276 '/W4', # Highest warning level.
277 '/WX', # Warnings as errors.
278 '/wd4530', '/wd4100', '/wd4706',
279 '/wd4512', '/wd4800', '/wd4702', '/wd4819',
280 # Disable warnings about passing "this" during initialization.
282 '/GR-', # Disable RTTI.
283 # Disable size_t -> int truncation warning.
284 # We never have strings or arrays larger than 2**31.
286 '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
287 '/D_VARIADIC_MAX=10',
288 '/DNINJA_PYTHON="%s"' % options.with_python]
289 if options.bootstrap:
290 # In bootstrap mode, we have no ninja process to catch /showIncludes
292 cflags.remove('/showIncludes')
293 if platform.msvc_needs_fs():
295 ldflags = ['/DEBUG', '/libpath:$builddir']
296 if not options.debug:
297 cflags += ['/Ox', '/DNDEBUG', '/GL']
298 ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
300 cflags = ['-g', '-Wall', '-Wextra',
302 '-Wno-unused-parameter',
305 '-fvisibility=hidden', '-pipe',
306 '-Wno-missing-field-initializers',
307 '-DNINJA_PYTHON="%s"' % options.with_python]
309 cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
310 cflags.remove('-fno-rtti') # Needed for above pedanticness.
312 cflags += ['-O2', '-DNDEBUG']
313 if 'clang' in os.path.basename(CXX):
314 cflags += ['-fcolor-diagnostics']
315 if platform.is_mingw():
316 cflags += ['-D_WIN32_WINNT=0x0501']
317 ldflags = ['-L$builddir']
318 if platform.uses_usr_local():
319 cflags.append('-I/usr/local/include')
320 ldflags.append('-L/usr/local/lib')
324 if platform.is_mingw():
325 cflags.remove('-fvisibility=hidden');
326 ldflags.append('-static')
327 elif platform.is_solaris():
328 cflags.remove('-fvisibility=hidden')
329 elif platform.is_msvc():
332 if options.profile == 'gmon':
334 ldflags.append('-pg')
335 elif options.profile == 'pprof':
336 cflags.append('-fno-omit-frame-pointer')
337 libs.extend(['-Wl,--no-as-needed', '-lprofiler'])
339 if platform.supports_ppoll() and not options.force_pselect:
340 cflags.append('-DUSE_PPOLL')
341 if platform.supports_ninja_browse():
342 cflags.append('-DNINJA_HAVE_BROWSE')
344 def shell_escape(str):
345 """Escape str such that it's interpreted as a single argument by
348 # This isn't complete, but it's just enough to make NINJA_PYTHON work.
349 if platform.is_windows():
352 return "'%s'" % str.replace("'", "\\'")
355 if 'CFLAGS' in configure_env:
356 cflags.append(configure_env['CFLAGS'])
357 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
358 if 'LDFLAGS' in configure_env:
359 ldflags.append(configure_env['LDFLAGS'])
360 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
363 if platform.is_msvc():
365 command='$cxx $cflags -c $in /Fo$out',
366 description='CXX $out',
367 deps='msvc' # /showIncludes is included in $cflags.
371 command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
374 description='CXX $out')
379 command='lib /nologo /ltcg /out:$out $in',
380 description='LIB $out')
381 elif host.is_mingw():
383 command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
384 description='AR $out')
387 command='rm -f $out && $ar crs $out $in',
388 description='AR $out')
391 if platform.is_msvc():
393 command='$cxx $in $libs /nologo /link $ldflags /out:$out',
394 description='LINK $out')
397 command='$cxx $ldflags -o $out $in $libs',
398 description='LINK $out')
403 if platform.supports_ninja_browse():
404 n.comment('browse_py.h is used to inline browse.py.')
406 command='src/inline.sh $varname < $in > $out',
407 description='INLINE $out')
408 n.build(built('browse_py.h'), 'inline', src('browse.py'),
409 implicit='src/inline.sh',
410 variables=[('varname', 'kBrowsePy')])
413 objs += cxx('browse', order_only=built('browse_py.h'))
416 n.comment('the depfile parser and ninja lexers are generated using re2c.')
419 proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
420 return int(proc.communicate()[0], 10) >= 1103
425 command='re2c -b -i --no-generation-date -o $out $in',
426 description='RE2C $out')
427 # Generate the .cc files in the source directory so we can check them in.
428 n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
429 n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
431 print("warning: A compatible version of re2c (>= 0.11.3) was not found; "
432 "changes to src/*.in.cc will not affect your build.")
435 n.comment('Core source files all build into ninja library.')
436 for name in ['build',
455 if platform.is_windows():
456 for name in ['subprocess-win32',
457 'includes_normalize-win32',
459 'msvc_helper_main-win32']:
461 if platform.is_msvc():
462 objs += cxx('minidump-win32')
465 objs += cxx('subprocess-posix')
466 if platform.is_msvc():
467 ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
469 ninja_lib = n.build(built('libninja.a'), 'ar', objs)
472 if platform.is_msvc():
473 libs.append('ninja.lib')
475 libs.append('-lninja')
479 n.comment('Main executable is library plus main() function.')
481 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
482 variables=[('libs', libs)])
486 if options.bootstrap:
487 # We've built the ninja binary. Don't run any more commands
488 # through the bootstrap executor, but continue writing the
492 n.comment('Tests all build into ninja_test executable.')
496 for name in ['build_log_test',
499 'depfile_parser_test',
501 'disk_interface_test',
502 'edit_distance_test',
505 'manifest_parser_test',
512 if platform.is_windows():
513 for name in ['includes_normalize_test', 'msvc_helper_test']:
516 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
517 variables=[('libs', libs)])
519 all_targets += ninja_test
522 n.comment('Ancillary executables.')
523 objs = cxx('build_log_perftest')
524 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
525 implicit=ninja_lib, variables=[('libs', libs)])
526 objs = cxx('canon_perftest')
527 all_targets += n.build(binary('canon_perftest'), 'link', objs,
528 implicit=ninja_lib, variables=[('libs', libs)])
529 objs = cxx('depfile_parser_perftest')
530 all_targets += n.build(binary('depfile_parser_perftest'), 'link', objs,
531 implicit=ninja_lib, variables=[('libs', libs)])
532 objs = cxx('hash_collision_bench')
533 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
534 implicit=ninja_lib, variables=[('libs', libs)])
535 objs = cxx('manifest_parser_perftest')
536 all_targets += n.build(binary('manifest_parser_perftest'), 'link', objs,
537 implicit=ninja_lib, variables=[('libs', libs)])
540 n.comment('Generate a graph using the "graph" tool.')
542 command='./ninja -t graph all > $out')
544 command='dot -Tpng $in > $out')
545 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
546 n.build('graph.png', 'gengraph', dot)
549 n.comment('Generate the manual using asciidoc.')
551 command='asciidoc -b docbook -d book -o $out $in',
552 description='ASCIIDOC $out')
554 command='xsltproc --nonet doc/docbook.xsl $in > $out',
555 description='XSLTPROC $out')
556 xml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
557 manual = n.build(doc('manual.html'), 'xsltproc', xml,
558 implicit=doc('style.css'))
559 n.build('manual', 'phony',
563 n.comment('Generate Doxygen.')
565 command='doxygen $in',
566 description='DOXYGEN $in')
567 n.variable('doxygen_mainpage_generator',
568 src('gen_doxygen_mainpage.sh'))
569 n.rule('doxygen_mainpage',
570 command='$doxygen_mainpage_generator $in > $out',
571 description='DOXYGEN_MAINPAGE $out')
572 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
573 ['README', 'COPYING'],
574 implicit=['$doxygen_mainpage_generator'])
575 n.build('doxygen', 'doxygen', doc('doxygen.config'),
579 if not host.is_mingw():
580 n.comment('Regenerate build files if build script changes.')
582 command='${configure_env}%s configure.py $configure_args' %
585 n.build('build.ninja', 'configure',
586 implicit=['configure.py', os.path.normpath('misc/ninja_syntax.py')])
593 n.comment('Packaging')
595 command="misc/packaging/rpmbuild.sh",
596 description='Building rpms..')
597 n.build('rpm', 'rpmbuild')
600 n.build('all', 'phony', all_targets)
603 print('wrote %s.' % BUILD_FILENAME)
605 if options.bootstrap:
606 print('bootstrap complete. rebuilding...')
607 if platform.is_windows():
608 bootstrap_exe = 'ninja.bootstrap.exe'
609 if os.path.exists(bootstrap_exe):
610 os.unlink(bootstrap_exe)
611 os.rename('ninja.exe', bootstrap_exe)
612 subprocess.check_call('ninja.bootstrap.exe', shell=True)
614 subprocess.check_call('./ninja', shell=True)