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