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