summaryrefslogtreecommitdiff
path: root/gn/build/gen.py
blob: 724d94c45c152ec4efddadb423b138dbe4ea1f76 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
#!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Generates build.ninja that will build GN."""

import contextlib
import errno
import optparse
import os
import platform
import re
import subprocess
import sys
import tempfile

try:  # py3
    from shlex import quote as shell_quote
except ImportError:  # py2
    from pipes import quote as shell_quote

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
REPO_ROOT = os.path.dirname(SCRIPT_DIR)


class Platform(object):
  """Represents a host/target platform."""
  def __init__(self, platform):
    self._platform = platform
    if self._platform is not None:
      return
    self._platform = sys.platform
    if self._platform.startswith('linux'):
      self._platform = 'linux'
    elif self._platform.startswith('darwin'):
      self._platform = 'darwin'
    elif self._platform.startswith('mingw'):
      self._platform = 'mingw'
    elif self._platform.startswith('msys'):
      self._platform = 'msys'
    elif self._platform.startswith('win'):
      self._platform = 'msvc'
    elif self._platform.startswith('aix'):
      self._platform = 'aix'
    elif self._platform.startswith('fuchsia'):
      self._platform = 'fuchsia'
    elif self._platform.startswith('freebsd'):
      self._platform = 'freebsd'
    elif self._platform.startswith('netbsd'):
      self._platform = 'netbsd'
    elif self._platform.startswith('openbsd'):
      self._platform = 'openbsd'
    elif self._platform.startswith('haiku'):
      self._platform = 'haiku'
    elif self._platform.startswith('sunos'):
      self._platform = 'solaris'

  @staticmethod
  def known_platforms():
    return ['linux', 'darwin', 'mingw', 'msys', 'msvc', 'aix', 'fuchsia', 'freebsd', 'netbsd', 'openbsd', 'haiku', 'solaris']

  def platform(self):
    return self._platform

  def is_linux(self):
    return self._platform == 'linux'

  def is_mingw(self):
    return self._platform == 'mingw'

  def is_msys(self):
    return self._platform == 'msys'

  def is_msvc(self):
    return self._platform == 'msvc'

  def is_windows(self):
    return self.is_mingw() or self.is_msvc()

  def is_darwin(self):
    return self._platform == 'darwin'

  def is_aix(self):
    return self._platform == 'aix'

  def is_haiku(self):
    return self._platform == 'haiku'

  def is_solaris(self):
    return self._platform == 'solaris'

  def is_posix(self):
    return self._platform in ['linux', 'freebsd', 'darwin', 'aix', 'openbsd', 'haiku', 'solaris', 'msys', 'netbsd']


def main(argv):
  parser = optparse.OptionParser(description=sys.modules[__name__].__doc__)
  parser.add_option('-d', '--debug', action='store_true',
                    help='Do a debug build. Defaults to release build.')
  parser.add_option('--platform',
                    help='target platform (' +
                         '/'.join(Platform.known_platforms()) + ')',
                    choices=Platform.known_platforms())
  parser.add_option('--host',
                    help='host platform (' +
                         '/'.join(Platform.known_platforms()) + ')',
                    choices=Platform.known_platforms())
  parser.add_option('--use-lto', action='store_true',
                    help='Enable the use of LTO')
  parser.add_option('--use-icf', action='store_true',
                    help='Enable the use of Identical Code Folding')
  parser.add_option('--no-last-commit-position', action='store_true',
                    help='Do not generate last_commit_position.h.')
  parser.add_option('--out-path',
                    help='The path to generate the build files in.')
  parser.add_option('--no-strip', action='store_true',
                    help='Don\'t strip release build. Useful for profiling.')
  parser.add_option('--no-static-libstdc++', action='store_true',
                    default=False, dest='no_static_libstdcpp',
                    help='Don\'t link libstdc++ statically')
  parser.add_option('--link-lib',
                    action='append',
                    metavar='LINK_LIB',
                    default=[],
                    dest='link_libs',
                    help=('Add a library to the final executable link. ' +
                          'LINK_LIB must be the path to a static or shared ' +
                          'library, or \'-l<name>\' on POSIX systems. Can be ' +
                          'used multiple times. Useful to link custom malloc ' +
                          'or cpu profiling libraries.'))
  parser.add_option('--cc',
                    help='The path to cc compiler.')
  parser.add_option('--cxx',
                    help='The path to cxx compiler.')
  parser.add_option('--ld',
                    help='The path to ld.')
  parser.add_option('--ar',
                    help='The path to ar.')
  parser.add_option('--isysroot',
                    help='The path to the macOS SDK sysroot to be used.')
  options, args = parser.parse_args(argv)

  if args:
    parser.error('Unrecognized command line arguments: %s.' % ', '.join(args))

  platform = Platform(options.platform)
  if options.host:
    host = Platform(options.host)
  else:
    host = platform

  out_dir = options.out_path or os.path.join(REPO_ROOT, 'out')
  if not os.path.isdir(out_dir):
    os.makedirs(out_dir)
  if not options.no_last_commit_position:
    GenerateLastCommitPosition(host,
                               os.path.join(out_dir, 'last_commit_position.h'))
  WriteGNNinja(os.path.join(out_dir, 'build.ninja'), platform, host, options)
  return 0


def GenerateLastCommitPosition(host, header):
  ROOT_TAG = 'initial-commit'
  describe_output = subprocess.check_output(
      ['git', 'describe', 'HEAD', '--match', ROOT_TAG], shell=host.is_windows(),
      cwd=REPO_ROOT)
  mo = re.match(ROOT_TAG + '-(\d+)-g([0-9a-f]+)', describe_output.decode())
  if not mo:
    raise ValueError(
        'Unexpected output from git describe when generating version header')

  contents = '''// Generated by build/gen.py.

#ifndef OUT_LAST_COMMIT_POSITION_H_
#define OUT_LAST_COMMIT_POSITION_H_

#define LAST_COMMIT_POSITION_NUM %s
#define LAST_COMMIT_POSITION "%s (%s)"

#endif  // OUT_LAST_COMMIT_POSITION_H_
''' % (mo.group(1), mo.group(1), mo.group(2))

  # Only write/touch this file if the commit position has changed.
  old_contents = ''
  if os.path.isfile(header):
    with open(header, 'r') as f:
      old_contents = f.read()

  if old_contents != contents:
    with open(header, 'w') as f:
      f.write(contents)


def WriteGenericNinja(path, static_libraries, executables,
                      cxx, ar, ld, platform, host, options,
                      cflags=[], ldflags=[], libflags=[],
                      include_dirs=[], solibs=[]):
  args = ' -d' if options.debug else ''
  for link_lib in options.link_libs:
    args +=  ' --link-lib=' + shell_quote(link_lib)

  ninja_header_lines = [
    'cxx = ' + cxx,
    'ar = ' + ar,
    'ld = ' + ld,
    '',
    'rule regen',
    '  command = %s ../build/gen.py%s' % (sys.executable, args),
    '  description = Regenerating ninja files',
    '',
    'build build.ninja: regen',
    '  generator = 1',
    '  depfile = build.ninja.d',
    '',
  ]


  template_filename = os.path.join(SCRIPT_DIR, {
      'msvc': 'build_win.ninja.template',
      'mingw': 'build_linux.ninja.template',
      'msys': 'build_linux.ninja.template',
      'darwin': 'build_mac.ninja.template',
      'linux': 'build_linux.ninja.template',
      'freebsd': 'build_linux.ninja.template',
      'aix': 'build_aix.ninja.template',
      'openbsd': 'build_openbsd.ninja.template',
      'haiku': 'build_haiku.ninja.template',
      'solaris': 'build_linux.ninja.template',
      'netbsd': 'build_linux.ninja.template',
  }[platform.platform()])

  with open(template_filename) as f:
    ninja_template = f.read()

  if platform.is_windows():
    executable_ext = '.exe'
    library_ext = '.lib'
    object_ext = '.obj'
  else:
    executable_ext = ''
    library_ext = '.a'
    object_ext = '.o'

  def escape_path_ninja(path):
      return path.replace('$ ', '$$ ').replace(' ', '$ ').replace(':', '$:')

  def src_to_obj(path):
    return escape_path_ninja('%s' % os.path.splitext(path)[0] + object_ext)

  def library_to_a(library):
    return '%s%s' % (library, library_ext)

  ninja_lines = []
  def build_source(src_file, settings):
    ninja_lines.extend([
        'build %s: cxx %s' % (src_to_obj(src_file),
                              escape_path_ninja(
                                  os.path.relpath(
                                      os.path.join(REPO_ROOT, src_file),
                                      os.path.dirname(path)))),
        '  includes = %s' % ' '.join(
            ['-I' + escape_path_ninja(dirname) for dirname in include_dirs]),
        '  cflags = %s' % ' '.join(cflags),
    ])

  for library, settings in static_libraries.items():
    for src_file in settings['sources']:
      build_source(src_file, settings)

    ninja_lines.append('build %s: alink_thin %s' % (
        library_to_a(library),
        ' '.join([src_to_obj(src_file) for src_file in settings['sources']])))
    ninja_lines.append('  libflags = %s' % ' '.join(libflags))


  for executable, settings in executables.items():
    for src_file in settings['sources']:
      build_source(src_file, settings)

    ninja_lines.extend([
      'build %s%s: link %s | %s' % (
          executable, executable_ext,
          ' '.join([src_to_obj(src_file) for src_file in settings['sources']]),
          ' '.join([library_to_a(library) for library in settings['libs']])),
      '  ldflags = %s' % ' '.join(ldflags),
      '  solibs = %s' % ' '.join(solibs),
      '  libs = %s' % ' '.join(
          [library_to_a(library) for library in settings['libs']]),
    ])

  ninja_lines.append('')  # Make sure the file ends with a newline.

  with open(path, 'w') as f:
    f.write('\n'.join(ninja_header_lines))
    f.write(ninja_template)
    f.write('\n'.join(ninja_lines))

  with open(path + '.d', 'w') as f:
    f.write('build.ninja: ' +
            os.path.relpath(os.path.join(SCRIPT_DIR, 'gen.py'),
                            os.path.dirname(path)) + ' ' +
            os.path.relpath(template_filename, os.path.dirname(path)) + '\n')


def WriteGNNinja(path, platform, host, options):
  # QTBUG-64759
  # if platform.is_msvc():
  #  cxx = os.environ.get('CXX', 'cl.exe')
  #  ld = os.environ.get('LD', 'link.exe')
  #  ar = os.environ.get('AR', 'lib.exe')
  #elif platform.is_aix():
  #  cxx = os.environ.get('CXX', 'g++')
  #  ld = os.environ.get('LD', 'g++')
  #  ar = os.environ.get('AR', 'ar -X64')
  #elif platform.is_msys() or platform.is_mingw():
  #  cxx = os.environ.get('CXX', 'g++')
  #  ld = os.environ.get('LD', 'g++')
  #  ar = os.environ.get('AR', 'ar')
  #else:
  #  cxx = os.environ.get('CXX', 'c++')
  #  ld = cxx
  #  ar = os.environ.get('AR', 'ar')

  # cflags = os.environ.get('CFLAGS', '').split()
  # cflags += os.environ.get('CXXFLAGS', '').split()
  # ldflags = os.environ.get('LDFLAGS', '').split()
  # libflags = os.environ.get('LIBFLAGS', '').split()

  cflags = []
  cflags_cc = []
  ldflags = []
  libflags = []

  cc = options.cc
  cxx = options.cxx
  ld = options.ld
  ar = options.ar

  if not ar:
     if platform.is_msvc():
        ar = os.environ.get('AR', 'lib.exe')
     else:
        ar = os.environ.get('AR', 'ar')

  include_dirs = [
      os.path.relpath(os.path.join(REPO_ROOT, 'src'), os.path.dirname(path)),
      '.',
  ]
  libs = []

  if not platform.is_msvc():
    if options.debug:
      cflags.extend(['-O0', '-g'])
    else:
      cflags.append('-DNDEBUG')
      cflags.append('-O3')
      if options.no_strip:
        cflags.append('-g')
      ldflags.append('-O3')
      if platform.is_darwin() and options.isysroot:
        cflags.append('-isysroot ' +  options.isysroot)
        ldflags.append('-isysroot ' +  options.isysroot)

      # Use -fdata-sections and -ffunction-sections to place each function
      # or data item into its own section so --gc-sections can eliminate any
      # unused functions and data items.
      cflags.extend(['-fdata-sections', '-ffunction-sections'])
      ldflags.extend(['-fdata-sections', '-ffunction-sections'])
      if platform.is_darwin():
        ldflags.append('-Wl,-dead_strip')
      elif not platform.is_aix() and not platform.is_solaris():
        # Garbage collection is done by default on aix.
        ldflags.append('-Wl,--gc-sections')

      # Omit all symbol information from the output file.
      if options.no_strip is None:
        if platform.is_darwin():
          ldflags.append('-Wl,-S')
        elif platform.is_aix():
          ldflags.append('-Wl,-s')
        elif platform.is_solaris():
          ldflags.append('-Wl,--strip-all')
        else:
          ldflags.append('-Wl,-strip-all')

      # Enable identical code-folding.
      if options.use_icf and not platform.is_darwin():
        ldflags.append('-Wl,--icf=all')

      if options.use_lto:
        cflags.extend(['-flto', '-fwhole-program-vtables'])
        ldflags.extend(['-flto', '-fwhole-program-vtables'])

    cflags.extend([
        '-D_FILE_OFFSET_BITS=64',
        '-D__STDC_CONSTANT_MACROS', '-D__STDC_FORMAT_MACROS',
        '-pthread',
        '-pipe',
        '-fno-exceptions',
        '-fno-rtti',
        '-fdiagnostics-color',
        '-Wall',
        '-Wextra',
        '-Wno-unused-parameter',
        '-std=c++17'
    ])

    if platform.is_linux() or platform.is_mingw() or platform.is_msys():
      ldflags.append('-Wl,--as-needed')

      if not options.no_static_libstdcpp:
        ldflags.append('-static-libstdc++')

      cflags.remove('-std=c++17')
      cflags.extend([
        '-Wno-deprecated-copy',
        '-Wno-implicit-fallthrough',
        '-Wno-redundant-move',
        '-Wno-unused-variable',
        '-Wno-format',             # Use of %llx, which is supported by _UCRT, false positive
        '-Wno-strict-aliasing',    # Dereferencing punned pointer
        '-Wno-cast-function-type', # Casting FARPROC to RegDeleteKeyExPtr
        '-std=gnu++17',
      ])
    elif platform.is_darwin():
      min_mac_version_flag = '-mmacosx-version-min=10.9'
      cflags.append(min_mac_version_flag)
      ldflags.append(min_mac_version_flag)
    elif platform.is_aix():
      cflags.append('-maix64')
      ldflags.append('-maix64')
    elif platform.is_haiku():
      cflags.append('-fPIC')
      cflags.extend(['-D_BSD_SOURCE'])

    if platform.is_posix() and not platform.is_haiku():
      ldflags.append('-pthread')

    if platform.is_mingw() or platform.is_msys():
      cflags.extend(['-DUNICODE',
                     '-DNOMINMAX',
                     '-DWIN32_LEAN_AND_MEAN',
                     '-DWINVER=0x0A00',
                     '-D_CRT_SECURE_NO_DEPRECATE',
                     '-D_SCL_SECURE_NO_DEPRECATE',
                     '-D_UNICODE',
                     '-D_WIN32_WINNT=0x0A00',
                     '-D_HAS_EXCEPTIONS=0'
      ])
  elif platform.is_msvc():
    if not options.debug:
      cflags.extend(['/O2', '/DNDEBUG', '/Zc:inline'])
      ldflags.extend(['/OPT:REF'])

      if options.use_icf:
        libflags.extend(['/OPT:ICF'])
      if options.use_lto:
        cflags.extend(['/GL'])
        libflags.extend(['/LTCG'])
        ldflags.extend(['/LTCG'])

    cflags.extend([
        '/DNOMINMAX',
        '/DUNICODE',
        '/DWIN32_LEAN_AND_MEAN',
        '/DWINVER=0x0A00',
        '/D_CRT_SECURE_NO_DEPRECATE',
        '/D_SCL_SECURE_NO_DEPRECATE',
        '/D_UNICODE',
        '/D_WIN32_WINNT=0x0A00',
        '/FS',
        '/W4',
        '/Zi',
        '/wd4099',
        '/wd4100',
        '/wd4127',
        '/wd4244',
        '/wd4267',
        '/wd4505',
        '/wd4577',
        '/wd4838',
        '/wd4996',
        '/std:c++17',
        '/GR-',
        '/D_HAS_EXCEPTIONS=0',
    ])

    target_arch = windows_target_build_arch()
    if target_arch == 'x64':
        ldflags.extend(['/MACHINE:x64'])
    else:
        ldflags.extend(['/MACHINE:x86'])

  static_libraries = {
      'base': {'sources': [
        'src/base/command_line.cc',
        'src/base/environment.cc',
        'src/base/files/file.cc',
        'src/base/files/file_enumerator.cc',
        'src/base/files/file_path.cc',
        'src/base/files/file_path_constants.cc',
        'src/base/files/file_util.cc',
        'src/base/files/scoped_file.cc',
        'src/base/files/scoped_temp_dir.cc',
        'src/base/json/json_parser.cc',
        'src/base/json/json_reader.cc',
        'src/base/json/json_writer.cc',
        'src/base/json/string_escape.cc',
        'src/base/logging.cc',
        'src/base/md5.cc',
        'src/base/memory/ref_counted.cc',
        'src/base/memory/weak_ptr.cc',
        'src/base/sha1.cc',
        'src/base/strings/string_number_conversions.cc',
        'src/base/strings/string_split.cc',
        'src/base/strings/string_util.cc',
        'src/base/strings/string_util_constants.cc',
        'src/base/strings/stringprintf.cc',
        'src/base/strings/utf_string_conversion_utils.cc',
        'src/base/strings/utf_string_conversions.cc',
        'src/base/third_party/icu/icu_utf.cc',
        'src/base/timer/elapsed_timer.cc',
        'src/base/value_iterators.cc',
        'src/base/values.cc',
      ]},
      'gn_lib': {'sources': [
        'src/gn/action_target_generator.cc',
        'src/gn/action_values.cc',
        'src/gn/analyzer.cc',
        'src/gn/args.cc',
        'src/gn/binary_target_generator.cc',
        'src/gn/build_settings.cc',
        'src/gn/builder.cc',
        'src/gn/builder_record.cc',
        'src/gn/bundle_data.cc',
        'src/gn/bundle_data_target_generator.cc',
        'src/gn/bundle_file_rule.cc',
        'src/gn/c_include_iterator.cc',
        'src/gn/c_substitution_type.cc',
        'src/gn/c_tool.cc',
        'src/gn/command_analyze.cc',
        'src/gn/command_args.cc',
        'src/gn/command_check.cc',
        'src/gn/command_clean.cc',
        'src/gn/command_clean_stale.cc',
        'src/gn/command_desc.cc',
        'src/gn/command_format.cc',
        'src/gn/command_gen.cc',
        'src/gn/command_help.cc',
        'src/gn/command_ls.cc',
        'src/gn/command_meta.cc',
        'src/gn/command_outputs.cc',
        'src/gn/command_path.cc',
        'src/gn/command_refs.cc',
        'src/gn/commands.cc',
        'src/gn/compile_commands_writer.cc',
        'src/gn/rust_project_writer.cc',
        'src/gn/config.cc',
        'src/gn/config_values.cc',
        'src/gn/config_values_extractors.cc',
        'src/gn/config_values_generator.cc',
        'src/gn/copy_target_generator.cc',
        'src/gn/create_bundle_target_generator.cc',
        'src/gn/deps_iterator.cc',
        'src/gn/desc_builder.cc',
        'src/gn/eclipse_writer.cc',
        'src/gn/err.cc',
        'src/gn/escape.cc',
        'src/gn/exec_process.cc',
        'src/gn/filesystem_utils.cc',
        'src/gn/file_writer.cc',
        'src/gn/frameworks_utils.cc',
        'src/gn/function_exec_script.cc',
        'src/gn/function_filter.cc',
        'src/gn/function_foreach.cc',
        'src/gn/function_forward_variables_from.cc',
        'src/gn/function_get_label_info.cc',
        'src/gn/function_get_path_info.cc',
        'src/gn/function_get_target_outputs.cc',
        'src/gn/function_process_file_template.cc',
        'src/gn/function_read_file.cc',
        'src/gn/function_rebase_path.cc',
        'src/gn/function_set_default_toolchain.cc',
        'src/gn/function_set_defaults.cc',
        'src/gn/function_template.cc',
        'src/gn/function_toolchain.cc',
        'src/gn/function_write_file.cc',
        'src/gn/functions.cc',
        'src/gn/functions_target.cc',
        'src/gn/general_tool.cc',
        'src/gn/generated_file_target_generator.cc',
        'src/gn/group_target_generator.cc',
        'src/gn/header_checker.cc',
        'src/gn/import_manager.cc',
        'src/gn/inherited_libraries.cc',
        'src/gn/input_conversion.cc',
        'src/gn/input_file.cc',
        'src/gn/input_file_manager.cc',
        'src/gn/item.cc',
        'src/gn/json_project_writer.cc',
        'src/gn/label.cc',
        'src/gn/label_pattern.cc',
        'src/gn/lib_file.cc',
        'src/gn/loader.cc',
        'src/gn/location.cc',
        'src/gn/metadata.cc',
        'src/gn/metadata_walk.cc',
        'src/gn/ninja_action_target_writer.cc',
        'src/gn/ninja_binary_target_writer.cc',
        'src/gn/ninja_build_writer.cc',
        'src/gn/ninja_bundle_data_target_writer.cc',
        'src/gn/ninja_c_binary_target_writer.cc',
        'src/gn/ninja_copy_target_writer.cc',
        'src/gn/ninja_create_bundle_target_writer.cc',
        'src/gn/ninja_generated_file_target_writer.cc',
        'src/gn/ninja_group_target_writer.cc',
        'src/gn/ninja_rust_binary_target_writer.cc',
        'src/gn/ninja_target_command_util.cc',
        'src/gn/ninja_target_writer.cc',
        'src/gn/ninja_toolchain_writer.cc',
        'src/gn/ninja_tools.cc',
        'src/gn/ninja_utils.cc',
        'src/gn/ninja_writer.cc',
        'src/gn/operators.cc',
        'src/gn/output_conversion.cc',
        'src/gn/output_file.cc',
        'src/gn/parse_node_value_adapter.cc',
        'src/gn/parse_tree.cc',
        'src/gn/parser.cc',
        'src/gn/path_output.cc',
        'src/gn/pattern.cc',
        'src/gn/pool.cc',
        'src/gn/qt_creator_writer.cc',
        'src/gn/runtime_deps.cc',
        'src/gn/rust_substitution_type.cc',
        'src/gn/rust_tool.cc',
        'src/gn/rust_values.cc',
        'src/gn/rust_values_generator.cc',
        'src/gn/rust_variables.cc',
        'src/gn/scheduler.cc',
        'src/gn/scope.cc',
        'src/gn/scope_per_file_provider.cc',
        'src/gn/settings.cc',
        'src/gn/setup.cc',
        'src/gn/source_dir.cc',
        'src/gn/source_file.cc',
        'src/gn/standard_out.cc',
        'src/gn/string_atom.cc',
        'src/gn/string_output_buffer.cc',
        'src/gn/string_utils.cc',
        'src/gn/substitution_list.cc',
        'src/gn/substitution_pattern.cc',
        'src/gn/substitution_type.cc',
        'src/gn/substitution_writer.cc',
        'src/gn/swift_values.cc',
        'src/gn/swift_values_generator.cc',
        'src/gn/swift_variables.cc',
        'src/gn/switches.cc',
        'src/gn/target.cc',
        'src/gn/target_generator.cc',
        'src/gn/template.cc',
        'src/gn/token.cc',
        'src/gn/tokenizer.cc',
        'src/gn/tool.cc',
        'src/gn/toolchain.cc',
        'src/gn/trace.cc',
        'src/gn/value.cc',
        'src/gn/value_extractors.cc',
        'src/gn/variables.cc',
        'src/gn/version.cc',
        'src/gn/visibility.cc',
        'src/gn/visual_studio_utils.cc',
        'src/gn/visual_studio_writer.cc',
        'src/gn/xcode_object.cc',
        'src/gn/xcode_writer.cc',
        'src/gn/xml_element_writer.cc',
        'src/util/exe_path.cc',
        'src/util/msg_loop.cc',
        'src/util/semaphore.cc',
        'src/util/sys_info.cc',
        'src/util/ticks.cc',
        'src/util/worker_pool.cc',
      ]},
  }

  executables = {
      'gn': {'sources': [ 'src/gn/gn_main.cc' ], 'libs': []},

      'gn_unittests': { 'sources': [
        'src/gn/action_target_generator_unittest.cc',
        'src/gn/analyzer_unittest.cc',
        'src/gn/args_unittest.cc',
        'src/gn/builder_unittest.cc',
        'src/gn/c_include_iterator_unittest.cc',
        'src/gn/command_format_unittest.cc',
        'src/gn/commands_unittest.cc',
        'src/gn/compile_commands_writer_unittest.cc',
        'src/gn/config_unittest.cc',
        'src/gn/config_values_extractors_unittest.cc',
        'src/gn/escape_unittest.cc',
        'src/gn/exec_process_unittest.cc',
        'src/gn/filesystem_utils_unittest.cc',
        'src/gn/file_writer_unittest.cc',
        'src/gn/frameworks_utils_unittest.cc',
        'src/gn/function_filter_unittest.cc',
        'src/gn/function_foreach_unittest.cc',
        'src/gn/function_forward_variables_from_unittest.cc',
        'src/gn/function_get_label_info_unittest.cc',
        'src/gn/function_get_path_info_unittest.cc',
        'src/gn/function_get_target_outputs_unittest.cc',
        'src/gn/function_process_file_template_unittest.cc',
        'src/gn/function_rebase_path_unittest.cc',
        'src/gn/function_template_unittest.cc',
        'src/gn/function_toolchain_unittest.cc',
        'src/gn/function_write_file_unittest.cc',
        'src/gn/functions_target_rust_unittest.cc',
        'src/gn/functions_target_unittest.cc',
        'src/gn/functions_unittest.cc',
        'src/gn/hash_table_base_unittest.cc',
        'src/gn/header_checker_unittest.cc',
        'src/gn/inherited_libraries_unittest.cc',
        'src/gn/input_conversion_unittest.cc',
        'src/gn/json_project_writer_unittest.cc',
        'src/gn/rust_project_writer_unittest.cc',
        'src/gn/rust_project_writer_helpers_unittest.cc',
        'src/gn/label_pattern_unittest.cc',
        'src/gn/label_unittest.cc',
        'src/gn/loader_unittest.cc',
        'src/gn/metadata_unittest.cc',
        'src/gn/metadata_walk_unittest.cc',
        'src/gn/ninja_action_target_writer_unittest.cc',
        'src/gn/ninja_binary_target_writer_unittest.cc',
        'src/gn/ninja_build_writer_unittest.cc',
        'src/gn/ninja_bundle_data_target_writer_unittest.cc',
        'src/gn/ninja_c_binary_target_writer_unittest.cc',
        'src/gn/ninja_copy_target_writer_unittest.cc',
        'src/gn/ninja_create_bundle_target_writer_unittest.cc',
        'src/gn/ninja_generated_file_target_writer_unittest.cc',
        'src/gn/ninja_group_target_writer_unittest.cc',
        'src/gn/ninja_rust_binary_target_writer_unittest.cc',
        'src/gn/ninja_target_command_util_unittest.cc',
        'src/gn/ninja_target_writer_unittest.cc',
        'src/gn/ninja_toolchain_writer_unittest.cc',
        'src/gn/operators_unittest.cc',
        'src/gn/output_conversion_unittest.cc',
        'src/gn/parse_tree_unittest.cc',
        'src/gn/parser_unittest.cc',
        'src/gn/path_output_unittest.cc',
        'src/gn/pattern_unittest.cc',
        'src/gn/runtime_deps_unittest.cc',
        'src/gn/scope_per_file_provider_unittest.cc',
        'src/gn/scope_unittest.cc',
        'src/gn/setup_unittest.cc',
        'src/gn/source_dir_unittest.cc',
        'src/gn/source_file_unittest.cc',
        'src/gn/string_atom_unittest.cc',
        'src/gn/string_output_buffer_unittest.cc',
        'src/gn/string_utils_unittest.cc',
        'src/gn/substitution_pattern_unittest.cc',
        'src/gn/substitution_writer_unittest.cc',
        'src/gn/target_unittest.cc',
        'src/gn/template_unittest.cc',
        'src/gn/test_with_scheduler.cc',
        'src/gn/test_with_scope.cc',
        'src/gn/tokenizer_unittest.cc',
        'src/gn/unique_vector_unittest.cc',
        'src/gn/value_unittest.cc',
        'src/gn/vector_utils_unittest.cc',
        'src/gn/version_unittest.cc',
        'src/gn/visibility_unittest.cc',
        'src/gn/visual_studio_utils_unittest.cc',
        'src/gn/visual_studio_writer_unittest.cc',
        'src/gn/xcode_object_unittest.cc',
        'src/gn/xml_element_writer_unittest.cc',
        'src/util/test/gn_test.cc',
      ], 'libs': []},
  }

  if platform.is_posix():
    static_libraries['base']['sources'].extend([
        'src/base/files/file_enumerator_posix.cc',
        'src/base/files/file_posix.cc',
        'src/base/files/file_util_posix.cc',
        'src/base/posix/file_descriptor_shuffle.cc',
        'src/base/posix/safe_strerror.cc',
    ])

  if platform.is_windows():
    static_libraries['base']['sources'].extend([
        'src/base/files/file_enumerator_win.cc',
        'src/base/files/file_util_win.cc',
        'src/base/files/file_win.cc',
        'src/base/win/registry.cc',
        'src/base/win/scoped_handle.cc',
        'src/base/win/scoped_process_information.cc',
    ])

    if platform.is_msvc():
      libs.extend([
          'advapi32.lib',
          'dbghelp.lib',
          'kernel32.lib',
          'ole32.lib',
          'shell32.lib',
          'user32.lib',
          'userenv.lib',
          'version.lib',
          'winmm.lib',
          'ws2_32.lib',
          'Shlwapi.lib',
      ])
    else:
      libs.extend([
          '-ladvapi32',
          '-ldbghelp',
          '-lkernel32',
          '-lole32',
          '-lshell32',
          '-luser32',
          '-luserenv',
          '-lversion',
          '-lwinmm',
          '-lws2_32',
          '-lshlwapi',
      ])


  libs.extend(options.link_libs)

  # we just build static libraries that GN needs
  executables['gn']['libs'].extend(static_libraries.keys())
  executables['gn_unittests']['libs'].extend(static_libraries.keys())

  WriteGenericNinja(path, static_libraries, executables, cxx, ar, ld,
                    platform, host, options, cflags, ldflags,
                    libflags, include_dirs, libs)

def windows_target_build_arch():
    target_arch = os.environ.get('Platform')
    if target_arch in ['x64', 'x86']: return target_arch

    if platform.machine().lower() in ['x86_64', 'amd64']: return 'x64'
    return 'x86'

if __name__ == '__main__':
  sys.exit(main(sys.argv[1:]))