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