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