Merge pull request #1106 from nico/winfix
[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('$root', 'src', filename)
271 def built(filename):
272     return os.path.join('$builddir', filename)
273 def doc(filename):
274     return os.path.join('$root', '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 root = sourcedir
287 if root == os.getcwd():
288     # In the common case where we're building directly in the source
289     # tree, simplify all the paths to just be cwd-relative.
290     root = '.'
291 n.variable('root', root)
292 n.variable('builddir', 'build')
293 n.variable('cxx', CXX)
294 if platform.is_msvc():
295     n.variable('ar', 'link')
296 else:
297     n.variable('ar', configure_env.get('AR', 'ar'))
298
299 if platform.is_msvc():
300     cflags = ['/showIncludes',
301               '/nologo',  # Don't print startup banner.
302               '/Zi',  # Create pdb with debug info.
303               '/W4',  # Highest warning level.
304               '/WX',  # Warnings as errors.
305               '/wd4530', '/wd4100', '/wd4706',
306               '/wd4512', '/wd4800', '/wd4702', '/wd4819',
307               # Disable warnings about constant conditional expressions.
308               '/wd4127',
309               # Disable warnings about passing "this" during initialization.
310               '/wd4355',
311               # Disable warnings about ignored typedef in DbgHelp.h
312               '/wd4091',
313               '/GR-',  # Disable RTTI.
314               # Disable size_t -> int truncation warning.
315               # We never have strings or arrays larger than 2**31.
316               '/wd4267',
317               '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
318               '/D_HAS_EXCEPTIONS=0',
319               '/DNINJA_PYTHON="%s"' % options.with_python]
320     if platform.msvc_needs_fs():
321         cflags.append('/FS')
322     ldflags = ['/DEBUG', '/libpath:$builddir']
323     if not options.debug:
324         cflags += ['/Ox', '/DNDEBUG', '/GL']
325         ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
326 else:
327     cflags = ['-g', '-Wall', '-Wextra',
328               '-Wno-deprecated',
329               '-Wno-missing-field-initializers',
330               '-Wno-unused-parameter',
331               '-fno-rtti',
332               '-fno-exceptions',
333               '-fvisibility=hidden', '-pipe',
334               '-DNINJA_PYTHON="%s"' % options.with_python]
335     if options.debug:
336         cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
337         cflags.remove('-fno-rtti')  # Needed for above pedanticness.
338     else:
339         cflags += ['-O2', '-DNDEBUG']
340     try:
341         proc = subprocess.Popen(
342             [CXX, '-fdiagnostics-color', '-c', '-x', 'c++', '/dev/null',
343              '-o', '/dev/null'],
344             stdout=open(os.devnull, 'wb'), stderr=subprocess.STDOUT)
345         if proc.wait() == 0:
346             cflags += ['-fdiagnostics-color']
347     except:
348         pass
349     if platform.is_mingw():
350         cflags += ['-D_WIN32_WINNT=0x0501']
351     ldflags = ['-L$builddir']
352     if platform.uses_usr_local():
353         cflags.append('-I/usr/local/include')
354         ldflags.append('-L/usr/local/lib')
355
356 libs = []
357
358 if platform.is_mingw():
359     cflags.remove('-fvisibility=hidden');
360     ldflags.append('-static')
361 elif platform.is_solaris():
362     cflags.remove('-fvisibility=hidden')
363 elif platform.is_aix():
364     cflags.remove('-fvisibility=hidden')
365 elif platform.is_msvc():
366     pass
367 else:
368     if options.profile == 'gmon':
369         cflags.append('-pg')
370         ldflags.append('-pg')
371     elif options.profile == 'pprof':
372         cflags.append('-fno-omit-frame-pointer')
373         libs.extend(['-Wl,--no-as-needed', '-lprofiler'])
374
375 if platform.supports_ppoll() and not options.force_pselect:
376     cflags.append('-DUSE_PPOLL')
377 if platform.supports_ninja_browse():
378     cflags.append('-DNINJA_HAVE_BROWSE')
379
380 # Search for generated headers relative to build dir.
381 cflags.append('-I.')
382
383 def shell_escape(str):
384     """Escape str such that it's interpreted as a single argument by
385     the shell."""
386
387     # This isn't complete, but it's just enough to make NINJA_PYTHON work.
388     if platform.is_windows():
389       return str
390     if '"' in str:
391         return "'%s'" % str.replace("'", "\\'")
392     return str
393
394 if 'CFLAGS' in configure_env:
395     cflags.append(configure_env['CFLAGS'])
396 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
397 if 'LDFLAGS' in configure_env:
398     ldflags.append(configure_env['LDFLAGS'])
399 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
400 n.newline()
401
402 if platform.is_msvc():
403     n.rule('cxx',
404         command='$cxx $cflags -c $in /Fo$out',
405         description='CXX $out',
406         deps='msvc'  # /showIncludes is included in $cflags.
407     )
408 else:
409     n.rule('cxx',
410         command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
411         depfile='$out.d',
412         deps='gcc',
413         description='CXX $out')
414 n.newline()
415
416 if host.is_msvc():
417     n.rule('ar',
418            command='lib /nologo /ltcg /out:$out $in',
419            description='LIB $out')
420 elif host.is_mingw():
421     n.rule('ar',
422            command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
423            description='AR $out')
424 else:
425     n.rule('ar',
426            command='rm -f $out && $ar crs $out $in',
427            description='AR $out')
428 n.newline()
429
430 if platform.is_msvc():
431     n.rule('link',
432         command='$cxx $in $libs /nologo /link $ldflags /out:$out',
433         description='LINK $out')
434 else:
435     n.rule('link',
436         command='$cxx $ldflags -o $out $in $libs',
437         description='LINK $out')
438 n.newline()
439
440 objs = []
441
442 if platform.supports_ninja_browse():
443     n.comment('browse_py.h is used to inline browse.py.')
444     n.rule('inline',
445            command='"%s"' % src('inline.sh') + ' $varname < $in > $out',
446            description='INLINE $out')
447     n.build(built('browse_py.h'), 'inline', src('browse.py'),
448             implicit=src('inline.sh'),
449             variables=[('varname', 'kBrowsePy')])
450     n.newline()
451
452     objs += cxx('browse', order_only=built('browse_py.h'))
453     n.newline()
454
455 n.comment('the depfile parser and ninja lexers are generated using re2c.')
456 def has_re2c():
457     try:
458         proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
459         return int(proc.communicate()[0], 10) >= 1103
460     except OSError:
461         return False
462 if has_re2c():
463     n.rule('re2c',
464            command='re2c -b -i --no-generation-date -o $out $in',
465            description='RE2C $out')
466     # Generate the .cc files in the source directory so we can check them in.
467     n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
468     n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
469 else:
470     print("warning: A compatible version of re2c (>= 0.11.3) was not found; "
471            "changes to src/*.in.cc will not affect your build.")
472 n.newline()
473
474 n.comment('Core source files all build into ninja library.')
475 for name in ['build',
476              'build_log',
477              'clean',
478              'debug_flags',
479              'depfile_parser',
480              'deps_log',
481              'disk_interface',
482              'edit_distance',
483              'eval_env',
484              'graph',
485              'graphviz',
486              'lexer',
487              'line_printer',
488              'manifest_parser',
489              'metrics',
490              'state',
491              'util',
492              'version']:
493     objs += cxx(name)
494 if platform.is_windows():
495     for name in ['subprocess-win32',
496                  'includes_normalize-win32',
497                  'msvc_helper-win32',
498                  'msvc_helper_main-win32']:
499         objs += cxx(name)
500     if platform.is_msvc():
501         objs += cxx('minidump-win32')
502     objs += cc('getopt')
503 else:
504     objs += cxx('subprocess-posix')
505 if platform.is_aix():
506     objs += cc('getopt')
507 if platform.is_msvc():
508     ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
509 else:
510     ninja_lib = n.build(built('libninja.a'), 'ar', objs)
511 n.newline()
512
513 if platform.is_msvc():
514     libs.append('ninja.lib')
515 else:
516     libs.append('-lninja')
517
518 if platform.is_aix():
519     libs.append('-lperfstat')
520
521 all_targets = []
522
523 n.comment('Main executable is library plus main() function.')
524 objs = cxx('ninja')
525 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
526                 variables=[('libs', libs)])
527 n.newline()
528 all_targets += ninja
529
530 if options.bootstrap:
531     # We've built the ninja binary.  Don't run any more commands
532     # through the bootstrap executor, but continue writing the
533     # build.ninja file.
534     n = ninja_writer
535
536 n.comment('Tests all build into ninja_test executable.')
537
538 objs = []
539
540 for name in ['build_log_test',
541              'build_test',
542              'clean_test',
543              'depfile_parser_test',
544              'deps_log_test',
545              'disk_interface_test',
546              'edit_distance_test',
547              'graph_test',
548              'lexer_test',
549              'manifest_parser_test',
550              'ninja_test',
551              'state_test',
552              'subprocess_test',
553              'test',
554              'util_test']:
555     objs += cxx(name)
556 if platform.is_windows():
557     for name in ['includes_normalize_test', 'msvc_helper_test']:
558         objs += cxx(name)
559
560 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
561                      variables=[('libs', libs)])
562 n.newline()
563 all_targets += ninja_test
564
565
566 n.comment('Ancillary executables.')
567 objs = cxx('build_log_perftest')
568 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
569                        implicit=ninja_lib, variables=[('libs', libs)])
570 objs = cxx('canon_perftest')
571 all_targets += n.build(binary('canon_perftest'), 'link', objs,
572                        implicit=ninja_lib, variables=[('libs', libs)])
573 objs = cxx('depfile_parser_perftest')
574 all_targets += n.build(binary('depfile_parser_perftest'), 'link', objs,
575                        implicit=ninja_lib, variables=[('libs', libs)])
576 objs = cxx('hash_collision_bench')
577 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
578                               implicit=ninja_lib, variables=[('libs', libs)])
579 objs = cxx('manifest_parser_perftest')
580 all_targets += n.build(binary('manifest_parser_perftest'), 'link', objs,
581                               implicit=ninja_lib, variables=[('libs', libs)])
582 n.newline()
583
584 n.comment('Generate a graph using the "graph" tool.')
585 n.rule('gendot',
586        command='./ninja -t graph all > $out')
587 n.rule('gengraph',
588        command='dot -Tpng $in > $out')
589 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
590 n.build('graph.png', 'gengraph', dot)
591 n.newline()
592
593 n.comment('Generate the manual using asciidoc.')
594 n.rule('asciidoc',
595        command='asciidoc -b docbook -d book -o $out $in',
596        description='ASCIIDOC $out')
597 n.rule('xsltproc',
598        command='xsltproc --nonet doc/docbook.xsl $in > $out',
599        description='XSLTPROC $out')
600 docbookxml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
601 manual = n.build(doc('manual.html'), 'xsltproc', docbookxml,
602                  implicit=[doc('style.css'), doc('docbook.xsl')])
603 n.build('manual', 'phony',
604         order_only=manual)
605 n.newline()
606
607 n.rule('dblatex',
608        command='dblatex -q -o $out -p doc/dblatex.xsl $in',
609        description='DBLATEX $out')
610 n.build(doc('manual.pdf'), 'dblatex', docbookxml,
611         implicit=[doc('dblatex.xsl')])
612
613 n.comment('Generate Doxygen.')
614 n.rule('doxygen',
615        command='doxygen $in',
616        description='DOXYGEN $in')
617 n.variable('doxygen_mainpage_generator',
618            src('gen_doxygen_mainpage.sh'))
619 n.rule('doxygen_mainpage',
620        command='$doxygen_mainpage_generator $in > $out',
621        description='DOXYGEN_MAINPAGE $out')
622 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
623                    ['README', 'COPYING'],
624                    implicit=['$doxygen_mainpage_generator'])
625 n.build('doxygen', 'doxygen', doc('doxygen.config'),
626         implicit=mainpage)
627 n.newline()
628
629 if not host.is_mingw():
630     n.comment('Regenerate build files if build script changes.')
631     n.rule('configure',
632            command='${configure_env}%s $root/configure.py $configure_args' %
633                options.with_python,
634            generator=True)
635     n.build('build.ninja', 'configure',
636             implicit=['$root/configure.py',
637                       os.path.normpath('$root/misc/ninja_syntax.py')])
638     n.newline()
639
640 n.default(ninja)
641 n.newline()
642
643 if host.is_linux():
644     n.comment('Packaging')
645     n.rule('rpmbuild',
646            command="misc/packaging/rpmbuild.sh",
647            description='Building rpms..')
648     n.build('rpm', 'rpmbuild')
649     n.newline()
650
651 n.build('all', 'phony', all_targets)
652
653 n.close()
654 print('wrote %s.' % BUILD_FILENAME)
655
656 if options.bootstrap:
657     print('bootstrap complete.  rebuilding...')
658
659     rebuild_args = []
660
661     if platform.can_rebuild_in_place():
662         rebuild_args.append('./ninja')
663     else:
664         if platform.is_windows():
665             bootstrap_exe = 'ninja.bootstrap.exe'
666             final_exe = 'ninja.exe'
667         else:
668             bootstrap_exe = './ninja.bootstrap'
669             final_exe = './ninja'
670
671         if os.path.exists(bootstrap_exe):
672             os.unlink(bootstrap_exe)
673         os.rename(final_exe, bootstrap_exe)
674
675         rebuild_args.append(bootstrap_exe)
676
677     if options.verbose:
678         rebuild_args.append('-v')
679
680     subprocess.check_call(rebuild_args)