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