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