1#!/usr/bin/env python
2# Copyright 2014 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Generates build.ninja that will build GN."""
7
8import contextlib
9import errno
10import optparse
11import os
12import platform
13import re
14import subprocess
15import sys
16import tempfile
17
18try:  # py3
19    from shlex import quote as shell_quote
20except ImportError:  # py2
21    from pipes import quote as shell_quote
22
23SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
24REPO_ROOT = os.path.dirname(SCRIPT_DIR)
25
26
27class Platform(object):
28  """Represents a host/target platform."""
29  def __init__(self, platform):
30    self._platform = platform
31    if self._platform is not None:
32      return
33    self._platform = sys.platform
34    if self._platform.startswith('linux'):
35      self._platform = 'linux'
36    elif self._platform.startswith('darwin'):
37      self._platform = 'darwin'
38    elif self._platform.startswith('mingw'):
39      self._platform = 'mingw'
40    elif self._platform.startswith('msys'):
41      self._platform = 'msys'
42    elif self._platform.startswith('win'):
43      self._platform = 'msvc'
44    elif self._platform.startswith('aix'):
45      self._platform = 'aix'
46    elif self._platform.startswith('fuchsia'):
47      self._platform = 'fuchsia'
48    elif self._platform.startswith('freebsd'):
49      self._platform = 'freebsd'
50    elif self._platform.startswith('netbsd'):
51      self._platform = 'netbsd'
52    elif self._platform.startswith('openbsd'):
53      self._platform = 'openbsd'
54    elif self._platform.lower().startswith('dragonfly'):
55      self._platform = 'dragonfly'
56    elif self._platform.startswith('haiku'):
57      self._platform = 'haiku'
58    elif self._platform.startswith('sunos'):
59      self._platform = 'solaris'
60
61  @staticmethod
62  def known_platforms():
63    return ['linux', 'darwin', 'mingw', 'msys', 'msvc', 'aix', 'fuchsia', 'freebsd', 'netbsd', 'openbsd', 'haiku', 'solaris', 'dragonfly']
64
65  def platform(self):
66    return self._platform
67
68  def is_linux(self):
69    return self._platform == 'linux'
70
71  def is_mingw(self):
72    return self._platform == 'mingw'
73
74  def is_msys(self):
75    return self._platform == 'msys'
76
77  def is_msvc(self):
78    return self._platform == 'msvc'
79
80  def is_windows(self):
81    return self.is_mingw() or self.is_msvc()
82
83  def is_darwin(self):
84    return self._platform == 'darwin'
85
86  def is_aix(self):
87    return self._platform == 'aix'
88
89  def is_haiku(self):
90    return self._platform == 'haiku'
91
92  def is_solaris(self):
93    return self._platform == 'solaris'
94
95  def is_freebsd(self):
96    return self._platform == 'freebsd'
97
98  def is_dragonfly(self):
99    return self._platform == 'dragonfly'
100
101  def is_posix(self):
102    return self._platform in ['linux', 'freebsd', 'darwin', 'aix', 'openbsd', 'haiku', 'solaris', 'msys', 'netbsd', 'dragonfly']
103
104
105def main(argv):
106  parser = optparse.OptionParser(description=sys.modules[__name__].__doc__)
107  parser.add_option('-d', '--debug', action='store_true',
108                    help='Do a debug build. Defaults to release build.')
109  parser.add_option('--platform',
110                    help='target platform (' +
111                         '/'.join(Platform.known_platforms()) + ')',
112                    choices=Platform.known_platforms())
113  parser.add_option('--host',
114                    help='host platform (' +
115                         '/'.join(Platform.known_platforms()) + ')',
116                    choices=Platform.known_platforms())
117  parser.add_option('--use-lto', action='store_true',
118                    help='Enable the use of LTO')
119  parser.add_option('--use-icf', action='store_true',
120                    help='Enable the use of Identical Code Folding')
121  parser.add_option('--no-last-commit-position', action='store_true',
122                    help='Do not generate last_commit_position.h.')
123  parser.add_option('--out-path',
124                    help='The path to generate the build files in.')
125  parser.add_option('--no-strip', action='store_true',
126                    help='Don\'t strip release build. Useful for profiling.')
127  parser.add_option('--no-static-libstdc++', action='store_true',
128                    default=False, dest='no_static_libstdcpp',
129                    help='Don\'t link libstdc++ statically')
130  parser.add_option('--link-lib',
131                    action='append',
132                    metavar='LINK_LIB',
133                    default=[],
134                    dest='link_libs',
135                    help=('Add a library to the final executable link. ' +
136                          'LINK_LIB must be the path to a static or shared ' +
137                          'library, or \'-l<name>\' on POSIX systems. Can be ' +
138                          'used multiple times. Useful to link custom malloc ' +
139                          'or cpu profiling libraries.'))
140  options, args = parser.parse_args(argv)
141
142  if args:
143    parser.error('Unrecognized command line arguments: %s.' % ', '.join(args))
144
145  platform = Platform(options.platform)
146  if options.host:
147    host = Platform(options.host)
148  else:
149    host = platform
150
151  out_dir = options.out_path or os.path.join(REPO_ROOT, 'out')
152  if not os.path.isdir(out_dir):
153    os.makedirs(out_dir)
154  if not options.no_last_commit_position:
155    GenerateLastCommitPosition(host,
156                               os.path.join(out_dir, 'last_commit_position.h'))
157  WriteGNNinja(os.path.join(out_dir, 'build.ninja'), platform, host, options)
158  return 0
159
160
161def GenerateLastCommitPosition(host, header):
162  ROOT_TAG = 'initial-commit'
163  describe_output = subprocess.check_output(
164      ['git', 'describe', 'HEAD', '--match', ROOT_TAG], shell=host.is_windows(),
165      cwd=REPO_ROOT)
166  mo = re.match(ROOT_TAG + '-(\d+)-g([0-9a-f]+)', describe_output.decode())
167  if not mo:
168    raise ValueError(
169        'Unexpected output from git describe when generating version header')
170
171  contents = '''// Generated by build/gen.py.
172
173#ifndef OUT_LAST_COMMIT_POSITION_H_
174#define OUT_LAST_COMMIT_POSITION_H_
175
176#define LAST_COMMIT_POSITION_NUM %s
177#define LAST_COMMIT_POSITION "%s (%s)"
178
179#endif  // OUT_LAST_COMMIT_POSITION_H_
180''' % (mo.group(1), mo.group(1), mo.group(2))
181
182  # Only write/touch this file if the commit position has changed.
183  old_contents = ''
184  if os.path.isfile(header):
185    with open(header, 'r') as f:
186      old_contents = f.read()
187
188  if old_contents != contents:
189    with open(header, 'w') as f:
190      f.write(contents)
191
192
193def WriteGenericNinja(path, static_libraries, executables,
194                      cxx, ar, ld, platform, host, options,
195                      cflags=[], ldflags=[], libflags=[],
196                      include_dirs=[], solibs=[]):
197  args = ' -d' if options.debug else ''
198  for link_lib in options.link_libs:
199    args +=  ' --link-lib=' + shell_quote(link_lib)
200
201  ninja_header_lines = [
202    'cxx = ' + cxx,
203    'ar = ' + ar,
204    'ld = ' + ld,
205    '',
206    'rule regen',
207    '  command = %s ../build/gen.py%s' % (sys.executable, args),
208    '  description = Regenerating ninja files',
209    '',
210    'build build.ninja: regen',
211    '  generator = 1',
212    '  depfile = build.ninja.d',
213    '',
214  ]
215
216
217  template_filename = os.path.join(SCRIPT_DIR, {
218      'msvc': 'build_win.ninja.template',
219      'mingw': 'build_linux.ninja.template',
220      'msys': 'build_linux.ninja.template',
221      'darwin': 'build_mac.ninja.template',
222      'linux': 'build_linux.ninja.template',
223      'freebsd': 'build_linux.ninja.template',
224      'dragonfly': 'build_linux.ninja.template',
225      'aix': 'build_aix.ninja.template',
226      'openbsd': 'build_openbsd.ninja.template',
227      'haiku': 'build_haiku.ninja.template',
228      'solaris': 'build_linux.ninja.template',
229      'netbsd': 'build_linux.ninja.template',
230  }[platform.platform()])
231
232  with open(template_filename) as f:
233    ninja_template = f.read()
234
235  if platform.is_windows():
236    executable_ext = '.exe'
237    library_ext = '.lib'
238    object_ext = '.obj'
239  else:
240    executable_ext = ''
241    library_ext = '.a'
242    object_ext = '.o'
243
244  def escape_path_ninja(path):
245      return path.replace('$ ', '$$ ').replace(' ', '$ ').replace(':', '$:')
246
247  def src_to_obj(path):
248    return escape_path_ninja('%s' % os.path.splitext(path)[0] + object_ext)
249
250  def library_to_a(library):
251    return '%s%s' % (library, library_ext)
252
253  ninja_lines = []
254  def build_source(src_file, settings):
255    ninja_lines.extend([
256        'build %s: cxx %s' % (src_to_obj(src_file),
257                              escape_path_ninja(
258                                  os.path.relpath(
259                                      os.path.join(REPO_ROOT, src_file),
260                                      os.path.dirname(path)))),
261        '  includes = %s' % ' '.join(
262            ['-I' + escape_path_ninja(dirname) for dirname in include_dirs]),
263        '  cflags = %s' % ' '.join(cflags),
264    ])
265
266  for library, settings in static_libraries.items():
267    for src_file in settings['sources']:
268      build_source(src_file, settings)
269
270    ninja_lines.append('build %s: alink_thin %s' % (
271        library_to_a(library),
272        ' '.join([src_to_obj(src_file) for src_file in settings['sources']])))
273    ninja_lines.append('  libflags = %s' % ' '.join(libflags))
274
275
276  for executable, settings in executables.items():
277    for src_file in settings['sources']:
278      build_source(src_file, settings)
279
280    ninja_lines.extend([
281      'build %s%s: link %s | %s' % (
282          executable, executable_ext,
283          ' '.join([src_to_obj(src_file) for src_file in settings['sources']]),
284          ' '.join([library_to_a(library) for library in settings['libs']])),
285      '  ldflags = %s' % ' '.join(ldflags),
286      '  solibs = %s' % ' '.join(solibs),
287      '  libs = %s' % ' '.join(
288          [library_to_a(library) for library in settings['libs']]),
289    ])
290
291  ninja_lines.append('')  # Make sure the file ends with a newline.
292
293  with open(path, 'w') as f:
294    f.write('\n'.join(ninja_header_lines))
295    f.write(ninja_template)
296    f.write('\n'.join(ninja_lines))
297
298  with open(path + '.d', 'w') as f:
299    f.write('build.ninja: ' +
300            os.path.relpath(os.path.join(SCRIPT_DIR, 'gen.py'),
301                            os.path.dirname(path)) + ' ' +
302            os.path.relpath(template_filename, os.path.dirname(path)) + '\n')
303
304
305def WriteGNNinja(path, platform, host, options):
306  if platform.is_msvc():
307    cxx = os.environ.get('CXX', 'cl.exe')
308    ld = os.environ.get('LD', 'link.exe')
309    ar = os.environ.get('AR', 'lib.exe')
310  elif platform.is_aix():
311    cxx = os.environ.get('CXX', 'g++')
312    ld = os.environ.get('LD', 'g++')
313    ar = os.environ.get('AR', 'ar -X64')
314  elif platform.is_msys() or platform.is_mingw():
315    cxx = os.environ.get('CXX', 'g++')
316    ld = os.environ.get('LD', 'g++')
317    ar = os.environ.get('AR', 'ar')
318  else:
319    cxx = os.environ.get('CXX', 'clang++')
320    ld = cxx
321    ar = os.environ.get('AR', 'ar')
322
323  cflags = os.environ.get('CFLAGS', '').split()
324  cflags += os.environ.get('CXXFLAGS', '').split()
325  ldflags = os.environ.get('LDFLAGS', '').split()
326  libflags = os.environ.get('LIBFLAGS', '').split()
327  include_dirs = [
328      os.path.relpath(os.path.join(REPO_ROOT, 'src'), os.path.dirname(path)),
329      '.',
330  ]
331  libs = []
332
333  if not platform.is_msvc():
334    if options.debug:
335      cflags.extend(['-O0', '-g'])
336    else:
337      cflags.append('-DNDEBUG')
338      cflags.append('-O3')
339      if options.no_strip:
340        cflags.append('-g')
341      ldflags.append('-O3')
342      # Use -fdata-sections and -ffunction-sections to place each function
343      # or data item into its own section so --gc-sections can eliminate any
344      # unused functions and data items.
345      cflags.extend(['-fdata-sections', '-ffunction-sections'])
346      ldflags.extend(['-fdata-sections', '-ffunction-sections'])
347      if platform.is_darwin():
348        ldflags.append('-Wl,-dead_strip')
349      elif not platform.is_aix() and not platform.is_solaris():
350        # Garbage collection is done by default on aix.
351        ldflags.append('-Wl,--gc-sections')
352
353      # Omit all symbol information from the output file.
354      if options.no_strip is None:
355        if platform.is_darwin():
356          ldflags.append('-Wl,-S')
357        elif platform.is_aix():
358          ldflags.append('-Wl,-s')
359        elif platform.is_solaris():
360          ldflags.append('-Wl,--strip-all')
361        else:
362          ldflags.append('-Wl,-strip-all')
363
364      # Enable identical code-folding.
365      if options.use_icf and not platform.is_darwin():
366        ldflags.append('-Wl,--icf=all')
367
368      if options.use_lto:
369        cflags.extend(['-flto', '-fwhole-program-vtables'])
370        ldflags.extend(['-flto', '-fwhole-program-vtables'])
371
372    cflags.extend([
373        '-D_FILE_OFFSET_BITS=64',
374        '-D__STDC_CONSTANT_MACROS', '-D__STDC_FORMAT_MACROS',
375        '-pthread',
376        '-pipe',
377        '-fno-exceptions',
378        '-fno-rtti',
379        '-fdiagnostics-color',
380        '-Wall',
381        '-Wextra',
382        '-Wno-unused-parameter',
383        '-std=c++17'
384    ])
385
386    if platform.is_linux() or platform.is_mingw() or platform.is_msys():
387      ldflags.append('-Wl,--as-needed')
388
389      if not options.no_static_libstdcpp:
390        ldflags.append('-static-libstdc++')
391
392      if platform.is_mingw() or platform.is_msys():
393        cflags.remove('-std=c++17')
394        cflags.extend([
395          '-Wno-deprecated-copy',
396          '-Wno-implicit-fallthrough',
397          '-Wno-redundant-move',
398          '-Wno-unused-variable',
399          '-Wno-format',             # Use of %llx, which is supported by _UCRT, false positive
400          '-Wno-strict-aliasing',    # Dereferencing punned pointer
401          '-Wno-cast-function-type', # Casting FARPROC to RegDeleteKeyExPtr
402          '-std=gnu++17',
403        ])
404      else:
405        # This is needed by libc++.
406        libs.append('-ldl')
407    elif platform.is_darwin():
408      min_mac_version_flag = '-mmacosx-version-min=10.9'
409      cflags.append(min_mac_version_flag)
410      ldflags.append(min_mac_version_flag)
411    elif platform.is_aix():
412      cflags.append('-maix64')
413      ldflags.append('-maix64')
414    elif platform.is_haiku():
415      cflags.append('-fPIC')
416      cflags.extend(['-D_BSD_SOURCE'])
417    elif platform.is_freebsd():
418      cflags.extend(['-Wno-deprecated-register', '-Wno-parentheses-equality'])
419      ldflags.extend(['-pthread'])
420      libs.extend(['-lexecinfo', '-lkvm', '-lutil'])
421      include_dirs += ['/usr/local/include']
422    elif platform.is_dragonfly():
423      cflags.extend(['-Wno-deprecated-register', '-Wno-parentheses-equality'])
424      ldflags.extend(['-pthread'])
425      libs.extend(['-lexecinfo', '-lkvm', '-lutil'])
426      include_dirs += ['/usr/local/include']
427
428    if platform.is_posix() and not platform.is_haiku():
429      ldflags.append('-pthread')
430
431    if platform.is_mingw() or platform.is_msys():
432      cflags.extend(['-DUNICODE',
433                     '-DNOMINMAX',
434                     '-DWIN32_LEAN_AND_MEAN',
435                     '-DWINVER=0x0A00',
436                     '-D_CRT_SECURE_NO_DEPRECATE',
437                     '-D_SCL_SECURE_NO_DEPRECATE',
438                     '-D_UNICODE',
439                     '-D_WIN32_WINNT=0x0A00',
440                     '-D_HAS_EXCEPTIONS=0'
441      ])
442  elif platform.is_msvc():
443    if not options.debug:
444      cflags.extend(['/O2', '/DNDEBUG', '/Zc:inline'])
445      ldflags.extend(['/OPT:REF'])
446
447      if options.use_icf:
448        libflags.extend(['/OPT:ICF'])
449      if options.use_lto:
450        cflags.extend(['/GL'])
451        libflags.extend(['/LTCG'])
452        ldflags.extend(['/LTCG'])
453
454    cflags.extend([
455        '/DNOMINMAX',
456        '/DUNICODE',
457        '/DWIN32_LEAN_AND_MEAN',
458        '/DWINVER=0x0A00',
459        '/D_CRT_SECURE_NO_DEPRECATE',
460        '/D_SCL_SECURE_NO_DEPRECATE',
461        '/D_UNICODE',
462        '/D_WIN32_WINNT=0x0A00',
463        '/FS',
464        '/W4',
465        '/WX',
466        '/Zi',
467        '/wd4099',
468        '/wd4100',
469        '/wd4127',
470        '/wd4244',
471        '/wd4267',
472        '/wd4505',
473        '/wd4838',
474        '/wd4996',
475        '/std:c++17',
476        '/GR-',
477        '/D_HAS_EXCEPTIONS=0',
478    ])
479
480    ldflags.extend(['/DEBUG', '/MACHINE:x64'])
481
482  static_libraries = {
483      'base': {'sources': [
484        'src/base/command_line.cc',
485        'src/base/environment.cc',
486        'src/base/files/file.cc',
487        'src/base/files/file_enumerator.cc',
488        'src/base/files/file_path.cc',
489        'src/base/files/file_path_constants.cc',
490        'src/base/files/file_util.cc',
491        'src/base/files/scoped_file.cc',
492        'src/base/files/scoped_temp_dir.cc',
493        'src/base/json/json_parser.cc',
494        'src/base/json/json_reader.cc',
495        'src/base/json/json_writer.cc',
496        'src/base/json/string_escape.cc',
497        'src/base/logging.cc',
498        'src/base/md5.cc',
499        'src/base/memory/ref_counted.cc',
500        'src/base/memory/weak_ptr.cc',
501        'src/base/sha1.cc',
502        'src/base/strings/string_number_conversions.cc',
503        'src/base/strings/string_split.cc',
504        'src/base/strings/string_util.cc',
505        'src/base/strings/string_util_constants.cc',
506        'src/base/strings/stringprintf.cc',
507        'src/base/strings/utf_string_conversion_utils.cc',
508        'src/base/strings/utf_string_conversions.cc',
509        'src/base/third_party/icu/icu_utf.cc',
510        'src/base/timer/elapsed_timer.cc',
511        'src/base/value_iterators.cc',
512        'src/base/values.cc',
513      ]},
514      'gn_lib': {'sources': [
515        'src/gn/action_target_generator.cc',
516        'src/gn/action_values.cc',
517        'src/gn/analyzer.cc',
518        'src/gn/args.cc',
519        'src/gn/binary_target_generator.cc',
520        'src/gn/build_settings.cc',
521        'src/gn/builder.cc',
522        'src/gn/builder_record.cc',
523        'src/gn/bundle_data.cc',
524        'src/gn/bundle_data_target_generator.cc',
525        'src/gn/bundle_file_rule.cc',
526        'src/gn/c_include_iterator.cc',
527        'src/gn/c_substitution_type.cc',
528        'src/gn/c_tool.cc',
529        'src/gn/command_analyze.cc',
530        'src/gn/command_args.cc',
531        'src/gn/command_check.cc',
532        'src/gn/command_clean.cc',
533        'src/gn/command_desc.cc',
534        'src/gn/command_format.cc',
535        'src/gn/command_gen.cc',
536        'src/gn/command_help.cc',
537        'src/gn/command_ls.cc',
538        'src/gn/command_meta.cc',
539        'src/gn/command_outputs.cc',
540        'src/gn/command_path.cc',
541        'src/gn/command_refs.cc',
542        'src/gn/commands.cc',
543        'src/gn/compile_commands_writer.cc',
544        'src/gn/rust_project_writer.cc',
545        'src/gn/config.cc',
546        'src/gn/config_values.cc',
547        'src/gn/config_values_extractors.cc',
548        'src/gn/config_values_generator.cc',
549        'src/gn/copy_target_generator.cc',
550        'src/gn/create_bundle_target_generator.cc',
551        'src/gn/deps_iterator.cc',
552        'src/gn/desc_builder.cc',
553        'src/gn/eclipse_writer.cc',
554        'src/gn/err.cc',
555        'src/gn/escape.cc',
556        'src/gn/exec_process.cc',
557        'src/gn/filesystem_utils.cc',
558        'src/gn/file_writer.cc',
559        'src/gn/frameworks_utils.cc',
560        'src/gn/function_exec_script.cc',
561        'src/gn/function_filter.cc',
562        'src/gn/function_foreach.cc',
563        'src/gn/function_forward_variables_from.cc',
564        'src/gn/function_get_label_info.cc',
565        'src/gn/function_get_path_info.cc',
566        'src/gn/function_get_target_outputs.cc',
567        'src/gn/function_process_file_template.cc',
568        'src/gn/function_read_file.cc',
569        'src/gn/function_rebase_path.cc',
570        'src/gn/function_set_default_toolchain.cc',
571        'src/gn/function_set_defaults.cc',
572        'src/gn/function_template.cc',
573        'src/gn/function_toolchain.cc',
574        'src/gn/function_write_file.cc',
575        'src/gn/functions.cc',
576        'src/gn/functions_target.cc',
577        'src/gn/general_tool.cc',
578        'src/gn/generated_file_target_generator.cc',
579        'src/gn/group_target_generator.cc',
580        'src/gn/header_checker.cc',
581        'src/gn/import_manager.cc',
582        'src/gn/inherited_libraries.cc',
583        'src/gn/input_conversion.cc',
584        'src/gn/input_file.cc',
585        'src/gn/input_file_manager.cc',
586        'src/gn/item.cc',
587        'src/gn/json_project_writer.cc',
588        'src/gn/label.cc',
589        'src/gn/label_pattern.cc',
590        'src/gn/lib_file.cc',
591        'src/gn/loader.cc',
592        'src/gn/location.cc',
593        'src/gn/metadata.cc',
594        'src/gn/metadata_walk.cc',
595        'src/gn/ninja_action_target_writer.cc',
596        'src/gn/ninja_binary_target_writer.cc',
597        'src/gn/ninja_build_writer.cc',
598        'src/gn/ninja_bundle_data_target_writer.cc',
599        'src/gn/ninja_c_binary_target_writer.cc',
600        'src/gn/ninja_copy_target_writer.cc',
601        'src/gn/ninja_create_bundle_target_writer.cc',
602        'src/gn/ninja_generated_file_target_writer.cc',
603        'src/gn/ninja_group_target_writer.cc',
604        'src/gn/ninja_rust_binary_target_writer.cc',
605        'src/gn/ninja_target_command_util.cc',
606        'src/gn/ninja_target_writer.cc',
607        'src/gn/ninja_toolchain_writer.cc',
608        'src/gn/ninja_utils.cc',
609        'src/gn/ninja_writer.cc',
610        'src/gn/operators.cc',
611        'src/gn/output_conversion.cc',
612        'src/gn/output_file.cc',
613        'src/gn/parse_node_value_adapter.cc',
614        'src/gn/parse_tree.cc',
615        'src/gn/parser.cc',
616        'src/gn/path_output.cc',
617        'src/gn/pattern.cc',
618        'src/gn/pool.cc',
619        'src/gn/qt_creator_writer.cc',
620        'src/gn/runtime_deps.cc',
621        'src/gn/rust_substitution_type.cc',
622        'src/gn/rust_tool.cc',
623        'src/gn/rust_values.cc',
624        'src/gn/rust_values_generator.cc',
625        'src/gn/rust_variables.cc',
626        'src/gn/scheduler.cc',
627        'src/gn/scope.cc',
628        'src/gn/scope_per_file_provider.cc',
629        'src/gn/settings.cc',
630        'src/gn/setup.cc',
631        'src/gn/source_dir.cc',
632        'src/gn/source_file.cc',
633        'src/gn/standard_out.cc',
634        'src/gn/string_atom.cc',
635        'src/gn/string_output_buffer.cc',
636        'src/gn/string_utils.cc',
637        'src/gn/substitution_list.cc',
638        'src/gn/substitution_pattern.cc',
639        'src/gn/substitution_type.cc',
640        'src/gn/substitution_writer.cc',
641        'src/gn/swift_values.cc',
642        'src/gn/swift_values_generator.cc',
643        'src/gn/swift_variables.cc',
644        'src/gn/switches.cc',
645        'src/gn/target.cc',
646        'src/gn/target_generator.cc',
647        'src/gn/template.cc',
648        'src/gn/token.cc',
649        'src/gn/tokenizer.cc',
650        'src/gn/tool.cc',
651        'src/gn/toolchain.cc',
652        'src/gn/trace.cc',
653        'src/gn/value.cc',
654        'src/gn/value_extractors.cc',
655        'src/gn/variables.cc',
656        'src/gn/version.cc',
657        'src/gn/visibility.cc',
658        'src/gn/visual_studio_utils.cc',
659        'src/gn/visual_studio_writer.cc',
660        'src/gn/xcode_object.cc',
661        'src/gn/xcode_writer.cc',
662        'src/gn/xml_element_writer.cc',
663        'src/util/exe_path.cc',
664        'src/util/msg_loop.cc',
665        'src/util/semaphore.cc',
666        'src/util/sys_info.cc',
667        'src/util/ticks.cc',
668        'src/util/worker_pool.cc',
669      ]},
670  }
671
672  executables = {
673      'gn': {'sources': [ 'src/gn/gn_main.cc' ], 'libs': []},
674
675      'gn_unittests': { 'sources': [
676        'src/gn/action_target_generator_unittest.cc',
677        'src/gn/analyzer_unittest.cc',
678        'src/gn/args_unittest.cc',
679        'src/gn/builder_unittest.cc',
680        'src/gn/c_include_iterator_unittest.cc',
681        'src/gn/command_format_unittest.cc',
682        'src/gn/commands_unittest.cc',
683        'src/gn/compile_commands_writer_unittest.cc',
684        'src/gn/config_unittest.cc',
685        'src/gn/config_values_extractors_unittest.cc',
686        'src/gn/escape_unittest.cc',
687        'src/gn/exec_process_unittest.cc',
688        'src/gn/filesystem_utils_unittest.cc',
689        'src/gn/file_writer_unittest.cc',
690        'src/gn/frameworks_utils_unittest.cc',
691        'src/gn/function_filter_unittest.cc',
692        'src/gn/function_foreach_unittest.cc',
693        'src/gn/function_forward_variables_from_unittest.cc',
694        'src/gn/function_get_label_info_unittest.cc',
695        'src/gn/function_get_path_info_unittest.cc',
696        'src/gn/function_get_target_outputs_unittest.cc',
697        'src/gn/function_process_file_template_unittest.cc',
698        'src/gn/function_rebase_path_unittest.cc',
699        'src/gn/function_template_unittest.cc',
700        'src/gn/function_toolchain_unittest.cc',
701        'src/gn/function_write_file_unittest.cc',
702        'src/gn/functions_target_rust_unittest.cc',
703        'src/gn/functions_target_unittest.cc',
704        'src/gn/functions_unittest.cc',
705        'src/gn/hash_table_base_unittest.cc',
706        'src/gn/header_checker_unittest.cc',
707        'src/gn/inherited_libraries_unittest.cc',
708        'src/gn/input_conversion_unittest.cc',
709        'src/gn/json_project_writer_unittest.cc',
710        'src/gn/rust_project_writer_unittest.cc',
711        'src/gn/rust_project_writer_helpers_unittest.cc',
712        'src/gn/label_pattern_unittest.cc',
713        'src/gn/label_unittest.cc',
714        'src/gn/loader_unittest.cc',
715        'src/gn/metadata_unittest.cc',
716        'src/gn/metadata_walk_unittest.cc',
717        'src/gn/ninja_action_target_writer_unittest.cc',
718        'src/gn/ninja_binary_target_writer_unittest.cc',
719        'src/gn/ninja_build_writer_unittest.cc',
720        'src/gn/ninja_bundle_data_target_writer_unittest.cc',
721        'src/gn/ninja_c_binary_target_writer_unittest.cc',
722        'src/gn/ninja_copy_target_writer_unittest.cc',
723        'src/gn/ninja_create_bundle_target_writer_unittest.cc',
724        'src/gn/ninja_generated_file_target_writer_unittest.cc',
725        'src/gn/ninja_group_target_writer_unittest.cc',
726        'src/gn/ninja_rust_binary_target_writer_unittest.cc',
727        'src/gn/ninja_target_command_util_unittest.cc',
728        'src/gn/ninja_target_writer_unittest.cc',
729        'src/gn/ninja_toolchain_writer_unittest.cc',
730        'src/gn/operators_unittest.cc',
731        'src/gn/output_conversion_unittest.cc',
732        'src/gn/parse_tree_unittest.cc',
733        'src/gn/parser_unittest.cc',
734        'src/gn/path_output_unittest.cc',
735        'src/gn/pattern_unittest.cc',
736        'src/gn/runtime_deps_unittest.cc',
737        'src/gn/scope_per_file_provider_unittest.cc',
738        'src/gn/scope_unittest.cc',
739        'src/gn/setup_unittest.cc',
740        'src/gn/source_dir_unittest.cc',
741        'src/gn/source_file_unittest.cc',
742        'src/gn/string_atom_unittest.cc',
743        'src/gn/string_output_buffer_unittest.cc',
744        'src/gn/string_utils_unittest.cc',
745        'src/gn/substitution_pattern_unittest.cc',
746        'src/gn/substitution_writer_unittest.cc',
747        'src/gn/target_unittest.cc',
748        'src/gn/template_unittest.cc',
749        'src/gn/test_with_scheduler.cc',
750        'src/gn/test_with_scope.cc',
751        'src/gn/tokenizer_unittest.cc',
752        'src/gn/unique_vector_unittest.cc',
753        'src/gn/value_unittest.cc',
754        'src/gn/vector_utils_unittest.cc',
755        'src/gn/version_unittest.cc',
756        'src/gn/visibility_unittest.cc',
757        'src/gn/visual_studio_utils_unittest.cc',
758        'src/gn/visual_studio_writer_unittest.cc',
759        'src/gn/xcode_object_unittest.cc',
760        'src/gn/xml_element_writer_unittest.cc',
761        'src/util/test/gn_test.cc',
762      ], 'libs': []},
763  }
764
765  if platform.is_posix():
766    static_libraries['base']['sources'].extend([
767        'src/base/files/file_enumerator_posix.cc',
768        'src/base/files/file_posix.cc',
769        'src/base/files/file_util_posix.cc',
770        'src/base/posix/file_descriptor_shuffle.cc',
771        'src/base/posix/safe_strerror.cc',
772    ])
773
774  if platform.is_windows():
775    static_libraries['base']['sources'].extend([
776        'src/base/files/file_enumerator_win.cc',
777        'src/base/files/file_util_win.cc',
778        'src/base/files/file_win.cc',
779        'src/base/win/registry.cc',
780        'src/base/win/scoped_handle.cc',
781        'src/base/win/scoped_process_information.cc',
782    ])
783
784    if platform.is_msvc():
785      libs.extend([
786          'advapi32.lib',
787          'dbghelp.lib',
788          'kernel32.lib',
789          'ole32.lib',
790          'shell32.lib',
791          'user32.lib',
792          'userenv.lib',
793          'version.lib',
794          'winmm.lib',
795          'ws2_32.lib',
796          'Shlwapi.lib',
797      ])
798    else:
799      libs.extend([
800          '-ladvapi32',
801          '-ldbghelp',
802          '-lkernel32',
803          '-lole32',
804          '-lshell32',
805          '-luser32',
806          '-luserenv',
807          '-lversion',
808          '-lwinmm',
809          '-lws2_32',
810          '-lshlwapi',
811      ])
812
813
814  libs.extend(options.link_libs)
815
816  # we just build static libraries that GN needs
817  executables['gn']['libs'].extend(static_libraries.keys())
818  executables['gn_unittests']['libs'].extend(static_libraries.keys())
819
820  WriteGenericNinja(path, static_libraries, executables, cxx, ar, ld,
821                    platform, host, options, cflags, ldflags,
822                    libflags, include_dirs, libs)
823
824
825if __name__ == '__main__':
826  sys.exit(main(sys.argv[1:]))
827