Merge pull request #979 from stinb/bootstrap-out-of-source
[platform/upstream/ninja.git] / configure.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2001 Google Inc. All Rights Reserved.
4 #
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
8 #
9 #     http://www.apache.org/licenses/LICENSE-2.0
10 #
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.
16
17 """Script that generates the build.ninja for ninja itself.
18
19 Projects that use ninja themselves should either write a similar script
20 or use a meta-build system that supports Ninja output."""
21
22 from __future__ import print_function
23
24 from optparse import OptionParser
25 import os
26 import pipes
27 import string
28 import subprocess
29 import sys
30
31 sourcedir = os.path.dirname(os.path.realpath(__file__))
32 sys.path.insert(0, os.path.join(sourcedir, 'misc'))
33 import ninja_syntax
34
35
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:
41             return
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
62     @staticmethod
63     def known_platforms():
64       return ['linux', 'darwin', 'freebsd', 'openbsd', 'solaris', 'sunos5',
65               'mingw', 'msvc', 'gnukfreebsd', 'bitrig', 'netbsd']
66
67     def platform(self):
68         return self._platform
69
70     def is_linux(self):
71         return self._platform == 'linux'
72
73     def is_mingw(self):
74         return self._platform == 'mingw'
75
76     def is_msvc(self):
77         return self._platform == 'msvc'
78
79     def msvc_needs_fs(self):
80         popen = subprocess.Popen(['cl', '/nologo', '/?'],
81                                  stdout=subprocess.PIPE,
82                                  stderr=subprocess.PIPE)
83         out, err = popen.communicate()
84         return '/FS ' in str(out)
85
86     def is_windows(self):
87         return self.is_mingw() or self.is_msvc()
88
89     def is_solaris(self):
90         return self._platform == 'solaris'
91
92     def uses_usr_local(self):
93         return self._platform in ('freebsd', 'openbsd', 'bitrig')
94
95     def supports_ppoll(self):
96         return self._platform in ('linux', 'openbsd', 'bitrig')
97
98     def supports_ninja_browse(self):
99         return not self.is_windows() and not self.is_solaris()
100
101
102 class Bootstrap:
103     """API shim for ninja_syntax.Writer that instead runs the commands.
104
105     Used to bootstrap Ninja from scratch.  In --bootstrap mode this
106     class is used to execute all the commands to build an executable.
107     It also proxies all calls to an underlying ninja_syntax.Writer, to
108     behave like non-bootstrap mode.
109     """
110     def __init__(self, writer, verbose=False):
111         self.writer = writer
112         self.verbose = verbose
113         # Map of variable name => expanded variable value.
114         self.vars = {}
115         # Map of rule name => dict of rule attributes.
116         self.rules = {
117             'phony': {}
118         }
119
120     def comment(self, text):
121         return self.writer.comment(text)
122
123     def newline(self):
124         return self.writer.newline()
125
126     def variable(self, key, val):
127         self.vars[key] = self._expand(val)
128         return self.writer.variable(key, val)
129
130     def rule(self, name, **kwargs):
131         self.rules[name] = kwargs
132         return self.writer.rule(name, **kwargs)
133
134     def build(self, outputs, rule, inputs=None, **kwargs):
135         ruleattr = self.rules[rule]
136         cmd = ruleattr.get('command')
137         if cmd is None:  # A phony rule, for example.
138             return
139
140         # Implement just enough of Ninja variable expansion etc. to
141         # make the bootstrap build work.
142         local_vars = {
143             'in': self._expand_paths(inputs),
144             'out': self._expand_paths(outputs)
145         }
146         for key, val in kwargs.get('variables', []):
147             local_vars[key] = ' '.join(ninja_syntax.as_list(val))
148
149         self._run_command(self._expand(cmd, local_vars))
150
151         return self.writer.build(outputs, rule, inputs, **kwargs)
152
153     def default(self, paths):
154         return self.writer.default(paths)
155
156     def _expand_paths(self, paths):
157         """Expand $vars in an array of paths, e.g. from a 'build' block."""
158         paths = ninja_syntax.as_list(paths)
159         return ' '.join(map(self._shell_escape, (map(self._expand, paths))))
160
161     def _expand(self, str, local_vars={}):
162         """Expand $vars in a string."""
163         return ninja_syntax.expand(str, self.vars, local_vars)
164
165     def _shell_escape(self, path):
166         """Quote paths containing spaces."""
167         return '"%s"' % path if ' ' in path else path
168
169     def _run_command(self, cmdline):
170         """Run a subcommand, quietly.  Prints the full command on error."""
171         try:
172             if self.verbose:
173                 print(cmdline)
174             subprocess.check_call(cmdline, shell=True)
175         except subprocess.CalledProcessError:
176             print('when running: ', cmdline)
177             raise
178
179
180 parser = OptionParser()
181 profilers = ['gmon', 'pprof']
182 parser.add_option('--bootstrap', action='store_true',
183                   help='bootstrap a ninja binary from nothing')
184 parser.add_option('--verbose', action='store_true',
185                   help='enable verbose build')
186 parser.add_option('--platform',
187                   help='target platform (' +
188                        '/'.join(Platform.known_platforms()) + ')',
189                   choices=Platform.known_platforms())
190 parser.add_option('--host',
191                   help='host platform (' +
192                        '/'.join(Platform.known_platforms()) + ')',
193                   choices=Platform.known_platforms())
194 parser.add_option('--debug', action='store_true',
195                   help='enable debugging extras',)
196 parser.add_option('--profile', metavar='TYPE',
197                   choices=profilers,
198                   help='enable profiling (' + '/'.join(profilers) + ')',)
199 parser.add_option('--with-gtest', metavar='PATH', help='ignored')
200 parser.add_option('--with-python', metavar='EXE',
201                   help='use EXE as the Python interpreter',
202                   default=os.path.basename(sys.executable))
203 parser.add_option('--force-pselect', action='store_true',
204                   help='ppoll() is used by default where available, '
205                        'but some platforms may need to use pselect instead',)
206 (options, args) = parser.parse_args()
207 if args:
208     print('ERROR: extra unparsed command-line arguments:', args)
209     sys.exit(1)
210
211 platform = Platform(options.platform)
212 if options.host:
213     host = Platform(options.host)
214 else:
215     host = platform
216
217 BUILD_FILENAME = 'build.ninja'
218 ninja_writer = ninja_syntax.Writer(open(BUILD_FILENAME, 'w'))
219 n = ninja_writer
220
221 if options.bootstrap:
222     # Make the build directory.
223     try:
224         os.mkdir('build')
225     except OSError:
226         pass
227     # Wrap ninja_writer with the Bootstrapper, which also executes the
228     # commands.
229     print('bootstrapping ninja...')
230     n = Bootstrap(n, verbose=options.verbose)
231
232 n.comment('This file is used to build ninja itself.')
233 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
234 n.newline()
235
236 n.variable('ninja_required_version', '1.3')
237 n.newline()
238
239 n.comment('The arguments passed to configure.py, for rerunning it.')
240 configure_args = sys.argv[1:]
241 if '--bootstrap' in configure_args:
242     configure_args.remove('--bootstrap')
243 n.variable('configure_args', ' '.join(configure_args))
244 env_keys = set(['CXX', 'AR', 'CFLAGS', 'LDFLAGS'])
245 configure_env = dict((k, os.environ[k]) for k in os.environ if k in env_keys)
246 if configure_env:
247     config_str = ' '.join([k + '=' + pipes.quote(configure_env[k])
248                            for k in configure_env])
249     n.variable('configure_env', config_str + '$ ')
250 n.newline()
251
252 CXX = configure_env.get('CXX', 'g++')
253 objext = '.o'
254 if platform.is_msvc():
255     CXX = 'cl'
256     objext = '.obj'
257
258 def src(filename):
259     return os.path.join('$sourcedir', 'src', filename)
260 def built(filename):
261     return os.path.join('$builddir', filename)
262 def doc(filename):
263     return os.path.join('$sourcedir', 'doc', filename)
264 def cc(name, **kwargs):
265     return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
266 def cxx(name, **kwargs):
267     return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
268 def binary(name):
269     if platform.is_windows():
270         exe = name + '.exe'
271         n.build(name, 'phony', exe)
272         return exe
273     return name
274
275 n.variable('sourcedir', sourcedir)
276 n.variable('builddir', 'build')
277 n.variable('cxx', CXX)
278 if platform.is_msvc():
279     n.variable('ar', 'link')
280 else:
281     n.variable('ar', configure_env.get('AR', 'ar'))
282
283 if platform.is_msvc():
284     cflags = ['/showIncludes',
285               '/nologo',  # Don't print startup banner.
286               '/Zi',  # Create pdb with debug info.
287               '/W4',  # Highest warning level.
288               '/WX',  # Warnings as errors.
289               '/wd4530', '/wd4100', '/wd4706',
290               '/wd4512', '/wd4800', '/wd4702', '/wd4819',
291               # Disable warnings about passing "this" during initialization.
292               '/wd4355',
293               # Disable warnings about ignored typedef in DbgHelp.h
294               '/wd4091',
295               '/GR-',  # Disable RTTI.
296               # Disable size_t -> int truncation warning.
297               # We never have strings or arrays larger than 2**31.
298               '/wd4267',
299               '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
300               '/DNINJA_PYTHON="%s"' % options.with_python]
301     if options.bootstrap:
302         # In bootstrap mode, we have no ninja process to catch /showIncludes
303         # output.
304         cflags.remove('/showIncludes')
305     if platform.msvc_needs_fs():
306         cflags.append('/FS')
307     ldflags = ['/DEBUG', '/libpath:$builddir']
308     if not options.debug:
309         cflags += ['/Ox', '/DNDEBUG', '/GL']
310         ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
311 else:
312     cflags = ['-g', '-Wall', '-Wextra',
313               '-Wno-deprecated',
314               '-Wno-unused-parameter',
315               '-fno-rtti',
316               '-fno-exceptions',
317               '-fvisibility=hidden', '-pipe',
318               '-Wno-missing-field-initializers',
319               '-DNINJA_PYTHON="%s"' % options.with_python]
320     if options.debug:
321         cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
322         cflags.remove('-fno-rtti')  # Needed for above pedanticness.
323     else:
324         cflags += ['-O2', '-DNDEBUG']
325     try:
326         proc = subprocess.Popen(
327             [CXX, '-fdiagnostics-color', '-c', '-x', 'c++', '/dev/null'],
328             stdout=open(os.devnull, 'wb'), stderr=subprocess.STDOUT)
329         if proc.wait() == 0:
330             cflags += ['-fdiagnostics-color']
331     except:
332         pass
333     if platform.is_mingw():
334         cflags += ['-D_WIN32_WINNT=0x0501']
335     ldflags = ['-L$builddir']
336     if platform.uses_usr_local():
337         cflags.append('-I/usr/local/include')
338         ldflags.append('-L/usr/local/lib')
339
340 libs = []
341
342 if platform.is_mingw():
343     cflags.remove('-fvisibility=hidden');
344     ldflags.append('-static')
345 elif platform.is_solaris():
346     cflags.remove('-fvisibility=hidden')
347 elif platform.is_msvc():
348     pass
349 else:
350     if options.profile == 'gmon':
351         cflags.append('-pg')
352         ldflags.append('-pg')
353     elif options.profile == 'pprof':
354         cflags.append('-fno-omit-frame-pointer')
355         libs.extend(['-Wl,--no-as-needed', '-lprofiler'])
356
357 if platform.supports_ppoll() and not options.force_pselect:
358     cflags.append('-DUSE_PPOLL')
359 if platform.supports_ninja_browse():
360     cflags.append('-DNINJA_HAVE_BROWSE')
361
362 # Search for generated headers relative to build dir.
363 cflags.append('-I.')
364
365 def shell_escape(str):
366     """Escape str such that it's interpreted as a single argument by
367     the shell."""
368
369     # This isn't complete, but it's just enough to make NINJA_PYTHON work.
370     if platform.is_windows():
371       return str
372     if '"' in str:
373         return "'%s'" % str.replace("'", "\\'")
374     return str
375
376 if 'CFLAGS' in configure_env:
377     cflags.append(configure_env['CFLAGS'])
378 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
379 if 'LDFLAGS' in configure_env:
380     ldflags.append(configure_env['LDFLAGS'])
381 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
382 n.newline()
383
384 if platform.is_msvc():
385     n.rule('cxx',
386         command='$cxx $cflags -c $in /Fo$out',
387         description='CXX $out',
388         deps='msvc'  # /showIncludes is included in $cflags.
389     )
390 else:
391     n.rule('cxx',
392         command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
393         depfile='$out.d',
394         deps='gcc',
395         description='CXX $out')
396 n.newline()
397
398 if host.is_msvc():
399     n.rule('ar',
400            command='lib /nologo /ltcg /out:$out $in',
401            description='LIB $out')
402 elif host.is_mingw():
403     n.rule('ar',
404            command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
405            description='AR $out')
406 else:
407     n.rule('ar',
408            command='rm -f $out && $ar crs $out $in',
409            description='AR $out')
410 n.newline()
411
412 if platform.is_msvc():
413     n.rule('link',
414         command='$cxx $in $libs /nologo /link $ldflags /out:$out',
415         description='LINK $out')
416 else:
417     n.rule('link',
418         command='$cxx $ldflags -o $out $in $libs',
419         description='LINK $out')
420 n.newline()
421
422 objs = []
423
424 if platform.supports_ninja_browse():
425     n.comment('browse_py.h is used to inline browse.py.')
426     n.rule('inline',
427            command='"%s"' % src('inline.sh') + ' $varname < $in > $out',
428            description='INLINE $out')
429     n.build(built('browse_py.h'), 'inline', src('browse.py'),
430             implicit=src('inline.sh'),
431             variables=[('varname', 'kBrowsePy')])
432     n.newline()
433
434     objs += cxx('browse', order_only=built('browse_py.h'))
435     n.newline()
436
437 n.comment('the depfile parser and ninja lexers are generated using re2c.')
438 def has_re2c():
439     try:
440         proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
441         return int(proc.communicate()[0], 10) >= 1103
442     except OSError:
443         return False
444 if has_re2c():
445     n.rule('re2c',
446            command='re2c -b -i --no-generation-date -o $out $in',
447            description='RE2C $out')
448     # Generate the .cc files in the source directory so we can check them in.
449     n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
450     n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
451 else:
452     print("warning: A compatible version of re2c (>= 0.11.3) was not found; "
453            "changes to src/*.in.cc will not affect your build.")
454 n.newline()
455
456 n.comment('Core source files all build into ninja library.')
457 for name in ['build',
458              'build_log',
459              'clean',
460              'debug_flags',
461              'depfile_parser',
462              'deps_log',
463              'disk_interface',
464              'edit_distance',
465              'eval_env',
466              'graph',
467              'graphviz',
468              'lexer',
469              'line_printer',
470              'manifest_parser',
471              'metrics',
472              'state',
473              'util',
474              'version']:
475     objs += cxx(name)
476 if platform.is_windows():
477     for name in ['subprocess-win32',
478                  'includes_normalize-win32',
479                  'msvc_helper-win32',
480                  'msvc_helper_main-win32']:
481         objs += cxx(name)
482     if platform.is_msvc():
483         objs += cxx('minidump-win32')
484     objs += cc('getopt')
485 else:
486     objs += cxx('subprocess-posix')
487 if platform.is_msvc():
488     ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
489 else:
490     ninja_lib = n.build(built('libninja.a'), 'ar', objs)
491 n.newline()
492
493 if platform.is_msvc():
494     libs.append('ninja.lib')
495 else:
496     libs.append('-lninja')
497
498 all_targets = []
499
500 n.comment('Main executable is library plus main() function.')
501 objs = cxx('ninja')
502 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
503                 variables=[('libs', libs)])
504 n.newline()
505 all_targets += ninja
506
507 if options.bootstrap:
508     # We've built the ninja binary.  Don't run any more commands
509     # through the bootstrap executor, but continue writing the
510     # build.ninja file.
511     n = ninja_writer
512
513 n.comment('Tests all build into ninja_test executable.')
514
515 objs = []
516
517 for name in ['build_log_test',
518              'build_test',
519              'clean_test',
520              'depfile_parser_test',
521              'deps_log_test',
522              'disk_interface_test',
523              'edit_distance_test',
524              'graph_test',
525              'lexer_test',
526              'manifest_parser_test',
527              'ninja_test',
528              'state_test',
529              'subprocess_test',
530              'test',
531              'util_test']:
532     objs += cxx(name)
533 if platform.is_windows():
534     for name in ['includes_normalize_test', 'msvc_helper_test']:
535         objs += cxx(name)
536
537 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
538                      variables=[('libs', libs)])
539 n.newline()
540 all_targets += ninja_test
541
542
543 n.comment('Ancillary executables.')
544 objs = cxx('build_log_perftest')
545 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
546                        implicit=ninja_lib, variables=[('libs', libs)])
547 objs = cxx('canon_perftest')
548 all_targets += n.build(binary('canon_perftest'), 'link', objs,
549                        implicit=ninja_lib, variables=[('libs', libs)])
550 objs = cxx('depfile_parser_perftest')
551 all_targets += n.build(binary('depfile_parser_perftest'), 'link', objs,
552                        implicit=ninja_lib, variables=[('libs', libs)])
553 objs = cxx('hash_collision_bench')
554 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
555                               implicit=ninja_lib, variables=[('libs', libs)])
556 objs = cxx('manifest_parser_perftest')
557 all_targets += n.build(binary('manifest_parser_perftest'), 'link', objs,
558                               implicit=ninja_lib, variables=[('libs', libs)])
559 n.newline()
560
561 n.comment('Generate a graph using the "graph" tool.')
562 n.rule('gendot',
563        command='./ninja -t graph all > $out')
564 n.rule('gengraph',
565        command='dot -Tpng $in > $out')
566 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
567 n.build('graph.png', 'gengraph', dot)
568 n.newline()
569
570 n.comment('Generate the manual using asciidoc.')
571 n.rule('asciidoc',
572        command='asciidoc -b docbook -d book -o $out $in',
573        description='ASCIIDOC $out')
574 n.rule('xsltproc',
575        command='xsltproc --nonet doc/docbook.xsl $in > $out',
576        description='XSLTPROC $out')
577 xml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
578 manual = n.build(doc('manual.html'), 'xsltproc', xml,
579                  implicit=doc('style.css'))
580 n.build('manual', 'phony',
581         order_only=manual)
582 n.newline()
583
584 n.comment('Generate Doxygen.')
585 n.rule('doxygen',
586        command='doxygen $in',
587        description='DOXYGEN $in')
588 n.variable('doxygen_mainpage_generator',
589            src('gen_doxygen_mainpage.sh'))
590 n.rule('doxygen_mainpage',
591        command='$doxygen_mainpage_generator $in > $out',
592        description='DOXYGEN_MAINPAGE $out')
593 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
594                    ['README', 'COPYING'],
595                    implicit=['$doxygen_mainpage_generator'])
596 n.build('doxygen', 'doxygen', doc('doxygen.config'),
597         implicit=mainpage)
598 n.newline()
599
600 if not host.is_mingw():
601     n.comment('Regenerate build files if build script changes.')
602     n.rule('configure',
603            command='${configure_env}%s $sourcedir/configure.py $configure_args' %
604                options.with_python,
605            generator=True)
606     n.build('build.ninja', 'configure',
607             implicit=['$sourcedir/configure.py',
608                       os.path.normpath('$sourcedir/misc/ninja_syntax.py')])
609     n.newline()
610
611 n.default(ninja)
612 n.newline()
613
614 if host.is_linux():
615     n.comment('Packaging')
616     n.rule('rpmbuild',
617            command="misc/packaging/rpmbuild.sh",
618            description='Building rpms..')
619     n.build('rpm', 'rpmbuild')
620     n.newline()
621
622 n.build('all', 'phony', all_targets)
623
624 n.close()
625 print('wrote %s.' % BUILD_FILENAME)
626
627 verbose = ''
628 if options.verbose:
629     verbose = ' -v'
630
631 if options.bootstrap:
632     print('bootstrap complete.  rebuilding...')
633     if platform.is_windows():
634         bootstrap_exe = 'ninja.bootstrap.exe'
635         if os.path.exists(bootstrap_exe):
636             os.unlink(bootstrap_exe)
637         os.rename('ninja.exe', bootstrap_exe)
638         subprocess.check_call('ninja.bootstrap.exe%s' % verbose, shell=True)
639     else:
640         subprocess.check_call('./ninja%s' % verbose, shell=True)