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