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