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