• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1from __future__ import print_function
2
3import json
4import sys
5import errno
6import optparse
7import os
8import pipes
9import pprint
10import re
11import shlex
12import subprocess
13import shutil
14import bz2
15import io
16
17# Fallback to find_executable from distutils.spawn is a stopgap for
18# supporting V8 builds, which do not yet support Python 3.
19try:
20  from shutil import which
21except ImportError:
22  from distutils.spawn import find_executable as which
23from distutils.version import StrictVersion
24
25# If not run from node/, cd to node/.
26os.chdir(os.path.dirname(__file__) or '.')
27
28original_argv = sys.argv[1:]
29
30# gcc and g++ as defaults matches what GYP's Makefile generator does,
31# except on OS X.
32CC = os.environ.get('CC', 'cc' if sys.platform == 'darwin' else 'gcc')
33CXX = os.environ.get('CXX', 'c++' if sys.platform == 'darwin' else 'g++')
34
35sys.path.insert(0, os.path.join('tools', 'gyp', 'pylib'))
36from gyp.common import GetFlavor
37
38# imports in tools/configure.d
39sys.path.insert(0, os.path.join('tools', 'configure.d'))
40import nodedownload
41
42# imports in tools/
43sys.path.insert(0, 'tools')
44import getmoduleversion
45import getnapibuildversion
46from gyp_node import run_gyp
47from utils import SearchFiles
48
49# imports in deps/v8/tools/node
50sys.path.insert(0, os.path.join('deps', 'v8', 'tools', 'node'))
51from fetch_deps import FetchDeps
52
53# parse our options
54parser = optparse.OptionParser()
55
56valid_os = ('win', 'mac', 'solaris', 'freebsd', 'openbsd', 'linux',
57            'android', 'aix', 'cloudabi')
58valid_arch = ('arm', 'arm64', 'ia32', 'mips', 'mipsel', 'mips64el', 'ppc',
59              'ppc64', 'x32','x64', 'x86', 'x86_64', 's390x')
60valid_arm_float_abi = ('soft', 'softfp', 'hard')
61valid_arm_fpu = ('vfp', 'vfpv3', 'vfpv3-d16', 'neon')
62valid_mips_arch = ('loongson', 'r1', 'r2', 'r6', 'rx')
63valid_mips_fpu = ('fp32', 'fp64', 'fpxx')
64valid_mips_float_abi = ('soft', 'hard')
65valid_intl_modes = ('none', 'small-icu', 'full-icu', 'system-icu')
66with open ('tools/icu/icu_versions.json') as f:
67  icu_versions = json.load(f)
68
69# create option groups
70shared_optgroup = optparse.OptionGroup(parser, "Shared libraries",
71    "Flags that allows you to control whether you want to build against "
72    "built-in dependencies or its shared representations. If necessary, "
73    "provide multiple libraries with comma.")
74intl_optgroup = optparse.OptionGroup(parser, "Internationalization",
75    "Flags that lets you enable i18n features in Node.js as well as which "
76    "library you want to build against.")
77http2_optgroup = optparse.OptionGroup(parser, "HTTP2",
78    "Flags that allows you to control HTTP2 features in Node.js")
79
80# Options should be in alphabetical order but keep --prefix at the top,
81# that's arguably the one people will be looking for most.
82parser.add_option('--prefix',
83    action='store',
84    dest='prefix',
85    default='/usr/local',
86    help='select the install prefix [default: %default]')
87
88parser.add_option('--coverage',
89    action='store_true',
90    dest='coverage',
91    help='Build node with code coverage enabled')
92
93parser.add_option('--debug',
94    action='store_true',
95    dest='debug',
96    help='also build debug build')
97
98parser.add_option('--debug-node',
99    action='store_true',
100    dest='debug_node',
101    help='build the Node.js part of the binary with debugging symbols')
102
103parser.add_option('--dest-cpu',
104    action='store',
105    dest='dest_cpu',
106    choices=valid_arch,
107    help='CPU architecture to build for ({0})'.format(', '.join(valid_arch)))
108
109parser.add_option('--cross-compiling',
110    action='store_true',
111    dest='cross_compiling',
112    default=None,
113    help='force build to be considered as cross compiled')
114parser.add_option('--no-cross-compiling',
115    action='store_false',
116    dest='cross_compiling',
117    default=None,
118    help='force build to be considered as NOT cross compiled')
119
120parser.add_option('--dest-os',
121    action='store',
122    dest='dest_os',
123    choices=valid_os,
124    help='operating system to build for ({0})'.format(', '.join(valid_os)))
125
126parser.add_option('--error-on-warn',
127    action='store_true',
128    dest='error_on_warn',
129    help='Turn compiler warnings into errors for node core sources.')
130
131parser.add_option('--gdb',
132    action='store_true',
133    dest='gdb',
134    help='add gdb support')
135
136parser.add_option('--no-ifaddrs',
137    action='store_true',
138    dest='no_ifaddrs',
139    help='use on deprecated SunOS systems that do not support ifaddrs.h')
140
141parser.add_option("--fully-static",
142    action="store_true",
143    dest="fully_static",
144    help="Generate an executable without external dynamic libraries. This "
145         "will not work on OSX when using the default compilation environment")
146
147parser.add_option("--partly-static",
148    action="store_true",
149    dest="partly_static",
150    help="Generate an executable with libgcc and libstdc++ libraries. This "
151         "will not work on OSX when using the default compilation environment")
152
153parser.add_option("--enable-pgo-generate",
154    action="store_true",
155    dest="enable_pgo_generate",
156    help="Enable profiling with pgo of a binary. This feature is only available "
157         "on linux with gcc and g++ 5.4.1 or newer.")
158
159parser.add_option("--enable-pgo-use",
160    action="store_true",
161    dest="enable_pgo_use",
162    help="Enable use of the profile generated with --enable-pgo-generate. This "
163         "feature is only available on linux with gcc and g++ 5.4.1 or newer.")
164
165parser.add_option("--enable-lto",
166    action="store_true",
167    dest="enable_lto",
168    help="Enable compiling with lto of a binary. This feature is only available "
169         "with gcc 5.4.1+ or clang 3.9.1+.")
170
171parser.add_option("--link-module",
172    action="append",
173    dest="linked_module",
174    help="Path to a JS file to be bundled in the binary as a builtin. "
175         "This module will be referenced by path without extension; "
176         "e.g. /root/x/y.js will be referenced via require('root/x/y'). "
177         "Can be used multiple times")
178
179parser.add_option("--openssl-conf-name",
180    action="store",
181    dest="openssl_conf_name",
182    default='nodejs_conf',
183    help="The OpenSSL config appname (config section name) used by Node.js")
184
185parser.add_option('--openssl-default-cipher-list',
186    action='store',
187    dest='openssl_default_cipher_list',
188    help='Use the specified cipher list as the default cipher list')
189
190parser.add_option("--openssl-no-asm",
191    action="store_true",
192    dest="openssl_no_asm",
193    help="Do not build optimized assembly for OpenSSL")
194
195parser.add_option('--openssl-fips',
196    action='store',
197    dest='openssl_fips',
198    help='Build OpenSSL using FIPS canister .o file in supplied folder')
199
200parser.add_option('--openssl-is-fips',
201    action='store_true',
202    dest='openssl_is_fips',
203    help='specifies that the OpenSSL library is FIPS compatible')
204
205parser.add_option('--openssl-use-def-ca-store',
206    action='store_true',
207    dest='use_openssl_ca_store',
208    help='Use OpenSSL supplied CA store instead of compiled-in Mozilla CA copy.')
209
210parser.add_option('--openssl-system-ca-path',
211    action='store',
212    dest='openssl_system_ca_path',
213    help='Use the specified path to system CA (PEM format) in addition to '
214         'the OpenSSL supplied CA store or compiled-in Mozilla CA copy.')
215
216parser.add_option('--experimental-http-parser',
217    action='store_true',
218    dest='experimental_http_parser',
219    help='(no-op)')
220
221shared_optgroup.add_option('--shared-http-parser',
222    action='store_true',
223    dest='shared_http_parser',
224    help='link to a shared http_parser DLL instead of static linking')
225
226shared_optgroup.add_option('--shared-http-parser-includes',
227    action='store',
228    dest='shared_http_parser_includes',
229    help='directory containing http_parser header files')
230
231shared_optgroup.add_option('--shared-http-parser-libname',
232    action='store',
233    dest='shared_http_parser_libname',
234    default='http_parser',
235    help='alternative lib name to link to [default: %default]')
236
237shared_optgroup.add_option('--shared-http-parser-libpath',
238    action='store',
239    dest='shared_http_parser_libpath',
240    help='a directory to search for the shared http_parser DLL')
241
242shared_optgroup.add_option('--shared-libuv',
243    action='store_true',
244    dest='shared_libuv',
245    help='link to a shared libuv DLL instead of static linking')
246
247shared_optgroup.add_option('--shared-libuv-includes',
248    action='store',
249    dest='shared_libuv_includes',
250    help='directory containing libuv header files')
251
252shared_optgroup.add_option('--shared-libuv-libname',
253    action='store',
254    dest='shared_libuv_libname',
255    default='uv',
256    help='alternative lib name to link to [default: %default]')
257
258shared_optgroup.add_option('--shared-libuv-libpath',
259    action='store',
260    dest='shared_libuv_libpath',
261    help='a directory to search for the shared libuv DLL')
262
263shared_optgroup.add_option('--shared-nghttp2',
264    action='store_true',
265    dest='shared_nghttp2',
266    help='link to a shared nghttp2 DLL instead of static linking')
267
268shared_optgroup.add_option('--shared-nghttp2-includes',
269    action='store',
270    dest='shared_nghttp2_includes',
271    help='directory containing nghttp2 header files')
272
273shared_optgroup.add_option('--shared-nghttp2-libname',
274    action='store',
275    dest='shared_nghttp2_libname',
276    default='nghttp2',
277    help='alternative lib name to link to [default: %default]')
278
279shared_optgroup.add_option('--shared-nghttp2-libpath',
280    action='store',
281    dest='shared_nghttp2_libpath',
282    help='a directory to search for the shared nghttp2 DLLs')
283
284shared_optgroup.add_option('--shared-openssl',
285    action='store_true',
286    dest='shared_openssl',
287    help='link to a shared OpenSSl DLL instead of static linking')
288
289shared_optgroup.add_option('--shared-openssl-includes',
290    action='store',
291    dest='shared_openssl_includes',
292    help='directory containing OpenSSL header files')
293
294shared_optgroup.add_option('--shared-openssl-libname',
295    action='store',
296    dest='shared_openssl_libname',
297    default='crypto,ssl',
298    help='alternative lib name to link to [default: %default]')
299
300shared_optgroup.add_option('--shared-openssl-libpath',
301    action='store',
302    dest='shared_openssl_libpath',
303    help='a directory to search for the shared OpenSSL DLLs')
304
305shared_optgroup.add_option('--shared-zlib',
306    action='store_true',
307    dest='shared_zlib',
308    help='link to a shared zlib DLL instead of static linking')
309
310shared_optgroup.add_option('--shared-zlib-includes',
311    action='store',
312    dest='shared_zlib_includes',
313    help='directory containing zlib header files')
314
315shared_optgroup.add_option('--shared-zlib-libname',
316    action='store',
317    dest='shared_zlib_libname',
318    default='z',
319    help='alternative lib name to link to [default: %default]')
320
321shared_optgroup.add_option('--shared-zlib-libpath',
322    action='store',
323    dest='shared_zlib_libpath',
324    help='a directory to search for the shared zlib DLL')
325
326shared_optgroup.add_option('--shared-brotli',
327    action='store_true',
328    dest='shared_brotli',
329    help='link to a shared brotli DLL instead of static linking')
330
331shared_optgroup.add_option('--shared-brotli-includes',
332    action='store',
333    dest='shared_brotli_includes',
334    help='directory containing brotli header files')
335
336shared_optgroup.add_option('--shared-brotli-libname',
337    action='store',
338    dest='shared_brotli_libname',
339    default='brotlidec,brotlienc',
340    help='alternative lib name to link to [default: %default]')
341
342shared_optgroup.add_option('--shared-brotli-libpath',
343    action='store',
344    dest='shared_brotli_libpath',
345    help='a directory to search for the shared brotli DLL')
346
347shared_optgroup.add_option('--shared-cares',
348    action='store_true',
349    dest='shared_cares',
350    help='link to a shared cares DLL instead of static linking')
351
352shared_optgroup.add_option('--shared-cares-includes',
353    action='store',
354    dest='shared_cares_includes',
355    help='directory containing cares header files')
356
357shared_optgroup.add_option('--shared-cares-libname',
358    action='store',
359    dest='shared_cares_libname',
360    default='cares',
361    help='alternative lib name to link to [default: %default]')
362
363shared_optgroup.add_option('--shared-cares-libpath',
364    action='store',
365    dest='shared_cares_libpath',
366    help='a directory to search for the shared cares DLL')
367
368parser.add_option_group(shared_optgroup)
369
370parser.add_option('--systemtap-includes',
371    action='store',
372    dest='systemtap_includes',
373    help='directory containing systemtap header files')
374
375parser.add_option('--tag',
376    action='store',
377    dest='tag',
378    help='custom build tag')
379
380parser.add_option('--release-urlbase',
381    action='store',
382    dest='release_urlbase',
383    help='Provide a custom URL prefix for the `process.release` properties '
384         '`sourceUrl` and `headersUrl`. When compiling a release build, this '
385         'will default to https://nodejs.org/download/release/')
386
387parser.add_option('--enable-d8',
388    action='store_true',
389    dest='enable_d8',
390    help=optparse.SUPPRESS_HELP)  # Unsupported, undocumented.
391
392parser.add_option('--enable-trace-maps',
393    action='store_true',
394    dest='trace_maps',
395    help='Enable the --trace-maps flag in V8 (use at your own risk)')
396
397parser.add_option('--experimental-enable-pointer-compression',
398    action='store_true',
399    dest='enable_pointer_compression',
400    help='[Experimental] Enable V8 pointer compression (limits max heap to 4GB and breaks ABI compatibility)')
401
402parser.add_option('--v8-options',
403    action='store',
404    dest='v8_options',
405    help='v8 options to pass, see `node --v8-options` for examples.')
406
407parser.add_option('--with-ossfuzz',
408    action='store_true',
409    dest='ossfuzz',
410    help='Enables building of fuzzers. This command should be run in an OSS-Fuzz Docker image.')
411
412parser.add_option('--with-arm-float-abi',
413    action='store',
414    dest='arm_float_abi',
415    choices=valid_arm_float_abi,
416    help='specifies which floating-point ABI to use ({0}).'.format(
417        ', '.join(valid_arm_float_abi)))
418
419parser.add_option('--with-arm-fpu',
420    action='store',
421    dest='arm_fpu',
422    choices=valid_arm_fpu,
423    help='ARM FPU mode ({0}) [default: %default]'.format(
424        ', '.join(valid_arm_fpu)))
425
426parser.add_option('--with-mips-arch-variant',
427    action='store',
428    dest='mips_arch_variant',
429    default='r2',
430    choices=valid_mips_arch,
431    help='MIPS arch variant ({0}) [default: %default]'.format(
432        ', '.join(valid_mips_arch)))
433
434parser.add_option('--with-mips-fpu-mode',
435    action='store',
436    dest='mips_fpu_mode',
437    default='fp32',
438    choices=valid_mips_fpu,
439    help='MIPS FPU mode ({0}) [default: %default]'.format(
440        ', '.join(valid_mips_fpu)))
441
442parser.add_option('--with-mips-float-abi',
443    action='store',
444    dest='mips_float_abi',
445    default='hard',
446    choices=valid_mips_float_abi,
447    help='MIPS floating-point ABI ({0}) [default: %default]'.format(
448        ', '.join(valid_mips_float_abi)))
449
450parser.add_option('--with-dtrace',
451    action='store_true',
452    dest='with_dtrace',
453    help='build with DTrace (default is true on sunos and darwin)')
454
455parser.add_option('--with-etw',
456    action='store_true',
457    dest='with_etw',
458    help='build with ETW (default is true on Windows)')
459
460parser.add_option('--use-largepages',
461    action='store_true',
462    dest='node_use_large_pages',
463    help='This option has no effect. --use-largepages is now a runtime option.')
464
465parser.add_option('--use-largepages-script-lld',
466    action='store_true',
467    dest='node_use_large_pages_script_lld',
468    help='This option has no effect. --use-largepages is now a runtime option.')
469
470parser.add_option('--use-section-ordering-file',
471    action='store',
472    dest='node_section_ordering_info',
473    default='',
474    help='Pass a section ordering file to the linker. This requires that ' +
475         'Node.js be linked using the gold linker. The gold linker must have ' +
476         'version 1.2 or greater.')
477
478intl_optgroup.add_option('--with-intl',
479    action='store',
480    dest='with_intl',
481    default='full-icu',
482    choices=valid_intl_modes,
483    help='Intl mode (valid choices: {0}) [default: %default]'.format(
484        ', '.join(valid_intl_modes)))
485
486intl_optgroup.add_option('--without-intl',
487    action='store_const',
488    dest='with_intl',
489    const='none',
490    help='Disable Intl, same as --with-intl=none (disables inspector)')
491
492intl_optgroup.add_option('--with-icu-path',
493    action='store',
494    dest='with_icu_path',
495    help='Path to icu.gyp (ICU i18n, Chromium version only.)')
496
497icu_default_locales='root,en'
498
499intl_optgroup.add_option('--with-icu-locales',
500    action='store',
501    dest='with_icu_locales',
502    default=icu_default_locales,
503    help='Comma-separated list of locales for "small-icu". "root" is assumed. '
504        '[default: %default]')
505
506intl_optgroup.add_option('--with-icu-source',
507    action='store',
508    dest='with_icu_source',
509    help='Intl mode: optional local path to icu/ dir, or path/URL of '
510        'the icu4c source archive. '
511        'v%d.x or later recommended.' % icu_versions['minimum_icu'])
512
513intl_optgroup.add_option('--with-icu-default-data-dir',
514    action='store',
515    dest='with_icu_default_data_dir',
516    help='Path to the icuXXdt{lb}.dat file. If unspecified, ICU data will '
517         'only be read if the NODE_ICU_DATA environment variable or the '
518         '--icu-data-dir runtime argument is used. This option has effect '
519         'only when Node.js is built with --with-intl=small-icu.')
520
521parser.add_option('--with-ltcg',
522    action='store_true',
523    dest='with_ltcg',
524    help='Use Link Time Code Generation. This feature is only available on Windows.')
525
526parser.add_option('--without-node-snapshot',
527    action='store_true',
528    dest='without_node_snapshot',
529    help='Turn off V8 snapshot integration. Currently experimental.')
530
531parser.add_option('--without-node-code-cache',
532    action='store_true',
533    dest='without_node_code_cache',
534    help='Turn off V8 Code cache integration.')
535
536intl_optgroup.add_option('--download',
537    action='store',
538    dest='download_list',
539    help=nodedownload.help())
540
541intl_optgroup.add_option('--download-path',
542    action='store',
543    dest='download_path',
544    default='deps',
545    help='Download directory [default: %default]')
546
547parser.add_option_group(intl_optgroup)
548
549parser.add_option('--debug-lib',
550    action='store_true',
551    dest='node_debug_lib',
552    help='build lib with DCHECK macros')
553
554http2_optgroup.add_option('--debug-nghttp2',
555    action='store_true',
556    dest='debug_nghttp2',
557    help='build nghttp2 with DEBUGBUILD (default is false)')
558
559parser.add_option_group(http2_optgroup)
560
561parser.add_option('--without-dtrace',
562    action='store_true',
563    dest='without_dtrace',
564    help='build without DTrace')
565
566parser.add_option('--without-etw',
567    action='store_true',
568    dest='without_etw',
569    help='build without ETW')
570
571parser.add_option('--without-npm',
572    action='store_true',
573    dest='without_npm',
574    help='do not install the bundled npm (package manager)')
575
576parser.add_option('--without-corepack',
577    action='store_true',
578    dest='without_corepack',
579    help='do not install the bundled Corepack')
580
581# Dummy option for backwards compatibility
582parser.add_option('--without-report',
583    action='store_true',
584    dest='unused_without_report',
585    help=optparse.SUPPRESS_HELP)
586
587parser.add_option('--with-snapshot',
588    action='store_true',
589    dest='unused_with_snapshot',
590    help=optparse.SUPPRESS_HELP)
591
592parser.add_option('--without-snapshot',
593    action='store_true',
594    dest='unused_without_snapshot',
595    help=optparse.SUPPRESS_HELP)
596
597parser.add_option('--without-siphash',
598    action='store_true',
599    dest='without_siphash',
600    help=optparse.SUPPRESS_HELP)
601
602# End dummy list.
603
604parser.add_option('--without-ssl',
605    action='store_true',
606    dest='without_ssl',
607    help='build without SSL (disables crypto, https, inspector, etc.)')
608
609parser.add_option('--without-node-options',
610    action='store_true',
611    dest='without_node_options',
612    help='build without NODE_OPTIONS support')
613
614parser.add_option('--ninja',
615    action='store_true',
616    dest='use_ninja',
617    help='generate build files for use with Ninja')
618
619parser.add_option('--enable-asan',
620    action='store_true',
621    dest='enable_asan',
622    help='compile for Address Sanitizer to find memory bugs')
623
624parser.add_option('--enable-static',
625    action='store_true',
626    dest='enable_static',
627    help='build as static library')
628
629parser.add_option('--no-browser-globals',
630    action='store_true',
631    dest='no_browser_globals',
632    help='do not export browser globals like setTimeout, console, etc. ' +
633         '(This mode is not officially supported for regular applications)')
634
635parser.add_option('--without-inspector',
636    action='store_true',
637    dest='without_inspector',
638    help='disable the V8 inspector protocol')
639
640parser.add_option('--shared',
641    action='store_true',
642    dest='shared',
643    help='compile shared library for embedding node in another project. ' +
644         '(This mode is not officially supported for regular applications)')
645
646parser.add_option('--without-v8-platform',
647    action='store_true',
648    dest='without_v8_platform',
649    default=False,
650    help='do not initialize v8 platform during node.js startup. ' +
651         '(This mode is not officially supported for regular applications)')
652
653parser.add_option('--without-bundled-v8',
654    action='store_true',
655    dest='without_bundled_v8',
656    default=False,
657    help='do not use V8 includes from the bundled deps folder. ' +
658         '(This mode is not officially supported for regular applications)')
659
660parser.add_option('--build-v8-with-gn',
661    action='store_true',
662    dest='build_v8_with_gn',
663    default=False,
664    help='build V8 using GN instead of gyp')
665
666parser.add_option('--verbose',
667    action='store_true',
668    dest='verbose',
669    default=False,
670    help='get more output from this script')
671
672parser.add_option('--v8-non-optimized-debug',
673    action='store_true',
674    dest='v8_non_optimized_debug',
675    default=False,
676    help='compile V8 with minimal optimizations and with runtime checks')
677
678parser.add_option('--v8-with-dchecks',
679    action='store_true',
680    dest='v8_with_dchecks',
681    default=False,
682    help='compile V8 with debug checks and runtime debugging features enabled')
683
684parser.add_option('--v8-lite-mode',
685    action='store_true',
686    dest='v8_lite_mode',
687    default=False,
688    help='compile V8 in lite mode for constrained environments (lowers V8 '+
689         'memory footprint, but also implies no just-in-time compilation ' +
690         'support, thus much slower execution)')
691
692parser.add_option('--v8-enable-object-print',
693    action='store_true',
694    dest='v8_enable_object_print',
695    default=True,
696    help='compile V8 with auxiliar functions for native debuggers')
697
698parser.add_option('--node-builtin-modules-path',
699    action='store',
700    dest='node_builtin_modules_path',
701    default=False,
702    help='node will load builtin modules from disk instead of from binary')
703
704# Create compile_commands.json in out/Debug and out/Release.
705parser.add_option('-C',
706    action='store_true',
707    dest='compile_commands_json',
708    help=optparse.SUPPRESS_HELP)
709
710(options, args) = parser.parse_args()
711
712# Expand ~ in the install prefix now, it gets written to multiple files.
713options.prefix = os.path.expanduser(options.prefix or '')
714
715# set up auto-download list
716auto_downloads = nodedownload.parse(options.download_list)
717
718
719def error(msg):
720  prefix = '\033[1m\033[31mERROR\033[0m' if os.isatty(1) else 'ERROR'
721  print('%s: %s' % (prefix, msg))
722  sys.exit(1)
723
724def warn(msg):
725  warn.warned = True
726  prefix = '\033[1m\033[93mWARNING\033[0m' if os.isatty(1) else 'WARNING'
727  print('%s: %s' % (prefix, msg))
728
729# track if warnings occurred
730warn.warned = False
731
732def info(msg):
733  prefix = '\033[1m\033[32mINFO\033[0m' if os.isatty(1) else 'INFO'
734  print('%s: %s' % (prefix, msg))
735
736def print_verbose(x):
737  if not options.verbose:
738    return
739  if type(x) is str:
740    print(x)
741  else:
742    pprint.pprint(x, indent=2)
743
744def b(value):
745  """Returns the string 'true' if value is truthy, 'false' otherwise."""
746  return 'true' if value else 'false'
747
748def B(value):
749  """Returns 1 if value is truthy, 0 otherwise."""
750  return 1 if value else 0
751
752def to_utf8(s):
753  return s if isinstance(s, str) else s.decode("utf-8")
754
755def pkg_config(pkg):
756  """Run pkg-config on the specified package
757  Returns ("-l flags", "-I flags", "-L flags", "version")
758  otherwise (None, None, None, None)"""
759  pkg_config = os.environ.get('PKG_CONFIG', 'pkg-config')
760  args = []  # Print pkg-config warnings on first round.
761  retval = ()
762  for flag in ['--libs-only-l', '--cflags-only-I',
763               '--libs-only-L', '--modversion']:
764    args += [flag]
765    if isinstance(pkg, list):
766      args += pkg
767    else:
768      args += [pkg]
769    try:
770      proc = subprocess.Popen(shlex.split(pkg_config) + args,
771                              stdout=subprocess.PIPE)
772      val = to_utf8(proc.communicate()[0]).strip()
773    except OSError as e:
774      if e.errno != errno.ENOENT: raise e  # Unexpected error.
775      return (None, None, None, None)  # No pkg-config/pkgconf installed.
776    retval += (val,)
777    args = ['--silence-errors']
778  return retval
779
780
781def try_check_compiler(cc, lang):
782  try:
783    proc = subprocess.Popen(shlex.split(cc) + ['-E', '-P', '-x', lang, '-'],
784                            stdin=subprocess.PIPE, stdout=subprocess.PIPE)
785  except OSError:
786    return (False, False, '', '')
787
788  proc.stdin.write(b'__clang__ __GNUC__ __GNUC_MINOR__ __GNUC_PATCHLEVEL__ '
789                   b'__clang_major__ __clang_minor__ __clang_patchlevel__')
790
791  values = (to_utf8(proc.communicate()[0]).split() + ['0'] * 7)[0:7]
792  is_clang = values[0] == '1'
793  gcc_version = tuple(map(int, values[1:1+3]))
794  clang_version = tuple(map(int, values[4:4+3])) if is_clang else None
795
796  return (True, is_clang, clang_version, gcc_version)
797
798
799#
800# The version of asm compiler is needed for building openssl asm files.
801# See deps/openssl/openssl.gypi for detail.
802# Commands and regular expressions to obtain its version number are taken from
803# https://github.com/openssl/openssl/blob/OpenSSL_1_0_2-stable/crypto/sha/asm/sha512-x86_64.pl#L112-L129
804#
805def get_version_helper(cc, regexp):
806  try:
807    proc = subprocess.Popen(shlex.split(cc) + ['-v'], stdin=subprocess.PIPE,
808                            stderr=subprocess.PIPE, stdout=subprocess.PIPE)
809  except OSError:
810    error('''No acceptable C compiler found!
811
812       Please make sure you have a C compiler installed on your system and/or
813       consider adjusting the CC environment variable if you installed
814       it in a non-standard prefix.''')
815
816  match = re.search(regexp, to_utf8(proc.communicate()[1]))
817
818  if match:
819    return match.group(2)
820  else:
821    return '0.0'
822
823def get_nasm_version(asm):
824  try:
825    proc = subprocess.Popen(shlex.split(asm) + ['-v'],
826                            stdin=subprocess.PIPE, stderr=subprocess.PIPE,
827                            stdout=subprocess.PIPE)
828  except OSError:
829    warn('''No acceptable ASM compiler found!
830         Please make sure you have installed NASM from https://www.nasm.us
831         and refer BUILDING.md.''')
832    return '0.0'
833
834  match = re.match(r"NASM version ([2-9]\.[0-9][0-9]+)",
835                   to_utf8(proc.communicate()[0]))
836
837  if match:
838    return match.group(1)
839  else:
840    return '0.0'
841
842def get_llvm_version(cc):
843  return get_version_helper(
844    cc, r"(^(?:.+ )?clang version|based on LLVM) ([0-9]+\.[0-9]+)")
845
846def get_xcode_version(cc):
847  return get_version_helper(
848    cc, r"(^Apple (?:clang|LLVM) version) ([0-9]+\.[0-9]+)")
849
850def get_gas_version(cc):
851  try:
852    custom_env = os.environ.copy()
853    custom_env["LC_ALL"] = "C"
854    proc = subprocess.Popen(shlex.split(cc) + ['-Wa,-v', '-c', '-o',
855                                               '/dev/null', '-x',
856                                               'assembler',  '/dev/null'],
857                            stdin=subprocess.PIPE, stderr=subprocess.PIPE,
858                            stdout=subprocess.PIPE, env=custom_env)
859  except OSError:
860    error('''No acceptable C compiler found!
861
862       Please make sure you have a C compiler installed on your system and/or
863       consider adjusting the CC environment variable if you installed
864       it in a non-standard prefix.''')
865
866  gas_ret = to_utf8(proc.communicate()[1])
867  match = re.match(r"GNU assembler version ([2-9]\.[0-9]+)", gas_ret)
868
869  if match:
870    return match.group(1)
871  else:
872    warn('Could not recognize `gas`: ' + gas_ret)
873    return '0.0'
874
875# Note: Apple clang self-reports as clang 4.2.0 and gcc 4.2.1.  It passes
876# the version check more by accident than anything else but a more rigorous
877# check involves checking the build number against an allowlist.  I'm not
878# quite prepared to go that far yet.
879def check_compiler(o):
880  if sys.platform == 'win32':
881    o['variables']['llvm_version'] = '0.0'
882    if not options.openssl_no_asm and options.dest_cpu in ('x86', 'x64'):
883      nasm_version = get_nasm_version('nasm')
884      o['variables']['nasm_version'] = nasm_version
885      if nasm_version == '0.0':
886        o['variables']['openssl_no_asm'] = 1
887    return
888
889  ok, is_clang, clang_version, gcc_version = try_check_compiler(CXX, 'c++')
890  version_str = ".".join(map(str, clang_version if is_clang else gcc_version))
891  print_verbose('Detected %sC++ compiler (CXX=%s) version: %s' %
892                ('clang ' if is_clang else '', CXX, version_str))
893  if not ok:
894    warn('failed to autodetect C++ compiler version (CXX=%s)' % CXX)
895  elif clang_version < (8, 0, 0) if is_clang else gcc_version < (6, 3, 0):
896    warn('C++ compiler (CXX=%s, %s) too old, need g++ 6.3.0 or clang++ 8.0.0' %
897         (CXX, version_str))
898
899  ok, is_clang, clang_version, gcc_version = try_check_compiler(CC, 'c')
900  version_str = ".".join(map(str, clang_version if is_clang else gcc_version))
901  print_verbose('Detected %sC compiler (CC=%s) version: %s' %
902                ('clang ' if is_clang else '', CC, version_str))
903  if not ok:
904    warn('failed to autodetect C compiler version (CC=%s)' % CC)
905  elif not is_clang and gcc_version < (4, 2, 0):
906    # clang 3.2 is a little white lie because any clang version will probably
907    # do for the C bits.  However, we might as well encourage people to upgrade
908    # to a version that is not completely ancient.
909    warn('C compiler (CC=%s, %s) too old, need gcc 4.2 or clang 3.2' %
910         (CC, version_str))
911
912  o['variables']['llvm_version'] = get_llvm_version(CC) if is_clang else '0.0'
913
914  # Need xcode_version or gas_version when openssl asm files are compiled.
915  if options.without_ssl or options.openssl_no_asm or options.shared_openssl:
916    return
917
918  if is_clang:
919    if sys.platform == 'darwin':
920      o['variables']['xcode_version'] = get_xcode_version(CC)
921  else:
922    o['variables']['gas_version'] = get_gas_version(CC)
923
924
925def cc_macros(cc=None):
926  """Checks predefined macros using the C compiler command."""
927
928  try:
929    p = subprocess.Popen(shlex.split(cc or CC) + ['-dM', '-E', '-'],
930                         stdin=subprocess.PIPE,
931                         stdout=subprocess.PIPE,
932                         stderr=subprocess.PIPE)
933  except OSError:
934    error('''No acceptable C compiler found!
935
936       Please make sure you have a C compiler installed on your system and/or
937       consider adjusting the CC environment variable if you installed
938       it in a non-standard prefix.''')
939
940  p.stdin.write(b'\n')
941  out = to_utf8(p.communicate()[0]).split('\n')
942
943  k = {}
944  for line in out:
945    lst = shlex.split(line)
946    if len(lst) > 2:
947      key = lst[1]
948      val = lst[2]
949      k[key] = val
950  return k
951
952
953def is_arch_armv7():
954  """Check for ARMv7 instructions"""
955  cc_macros_cache = cc_macros()
956  return cc_macros_cache.get('__ARM_ARCH') == '7'
957
958
959def is_arch_armv6():
960  """Check for ARMv6 instructions"""
961  cc_macros_cache = cc_macros()
962  return cc_macros_cache.get('__ARM_ARCH') == '6'
963
964
965def is_arm_hard_float_abi():
966  """Check for hardfloat or softfloat eabi on ARM"""
967  # GCC versions 4.6 and above define __ARM_PCS or __ARM_PCS_VFP to specify
968  # the Floating Point ABI used (PCS stands for Procedure Call Standard).
969  # We use these as well as a couple of other defines to statically determine
970  # what FP ABI used.
971
972  return '__ARM_PCS_VFP' in cc_macros()
973
974
975def host_arch_cc():
976  """Host architecture check using the CC command."""
977
978  k = cc_macros(os.environ.get('CC_host'))
979
980  matchup = {
981    '__aarch64__' : 'arm64',
982    '__arm__'     : 'arm',
983    '__i386__'    : 'ia32',
984    '__MIPSEL__'  : 'mipsel',
985    '__mips__'    : 'mips',
986    '__PPC64__'   : 'ppc64',
987    '__PPC__'     : 'ppc64',
988    '__x86_64__'  : 'x64',
989    '__s390x__'   : 's390x',
990  }
991
992  rtn = 'ia32' # default
993
994  for i in matchup:
995    if i in k and k[i] != '0':
996      rtn = matchup[i]
997      break
998
999  if rtn == 'mipsel' and '_LP64' in k:
1000    rtn = 'mips64el'
1001
1002  return rtn
1003
1004
1005def host_arch_win():
1006  """Host architecture check using environ vars (better way to do this?)"""
1007
1008  observed_arch = os.environ.get('PROCESSOR_ARCHITECTURE', 'x86')
1009  arch = os.environ.get('PROCESSOR_ARCHITEW6432', observed_arch)
1010
1011  matchup = {
1012    'AMD64'  : 'x64',
1013    'x86'    : 'ia32',
1014    'arm'    : 'arm',
1015    'mips'   : 'mips',
1016  }
1017
1018  return matchup.get(arch, 'ia32')
1019
1020
1021def configure_arm(o):
1022  if options.arm_float_abi:
1023    arm_float_abi = options.arm_float_abi
1024  elif is_arm_hard_float_abi():
1025    arm_float_abi = 'hard'
1026  else:
1027    arm_float_abi = 'default'
1028
1029  arm_fpu = 'vfp'
1030
1031  if is_arch_armv7():
1032    arm_fpu = 'vfpv3'
1033    o['variables']['arm_version'] = '7'
1034  else:
1035    o['variables']['arm_version'] = '6' if is_arch_armv6() else 'default'
1036
1037  o['variables']['arm_thumb'] = 0      # -marm
1038  o['variables']['arm_float_abi'] = arm_float_abi
1039
1040  if options.dest_os == 'android':
1041    arm_fpu = 'vfpv3'
1042    o['variables']['arm_version'] = '7'
1043
1044  o['variables']['arm_fpu'] = options.arm_fpu or arm_fpu
1045
1046
1047def configure_mips(o, target_arch):
1048  can_use_fpu_instructions = (options.mips_float_abi != 'soft')
1049  o['variables']['v8_can_use_fpu_instructions'] = b(can_use_fpu_instructions)
1050  o['variables']['v8_use_mips_abi_hardfloat'] = b(can_use_fpu_instructions)
1051  o['variables']['mips_arch_variant'] = options.mips_arch_variant
1052  o['variables']['mips_fpu_mode'] = options.mips_fpu_mode
1053  host_byteorder = 'little' if target_arch in ('mipsel', 'mips64el') else 'big'
1054  o['variables']['v8_host_byteorder'] = host_byteorder
1055
1056def clang_version_ge(version_checked):
1057  for compiler in [(CC, 'c'), (CXX, 'c++')]:
1058    ok, is_clang, clang_version, gcc_version = \
1059      try_check_compiler(compiler[0], compiler[1])
1060    if is_clang and clang_version >= version_checked:
1061      return True
1062  return False
1063
1064def gcc_version_ge(version_checked):
1065  for compiler in [(CC, 'c'), (CXX, 'c++')]:
1066    ok, is_clang, clang_version, gcc_version = \
1067      try_check_compiler(compiler[0], compiler[1])
1068    if is_clang or gcc_version < version_checked:
1069      return False
1070  return True
1071
1072def configure_node_lib_files(o):
1073  o['variables']['node_library_files'] = SearchFiles('lib', 'js')
1074
1075def configure_node(o):
1076  if options.dest_os == 'android':
1077    o['variables']['OS'] = 'android'
1078  o['variables']['node_prefix'] = options.prefix
1079  o['variables']['node_install_npm'] = b(not options.without_npm)
1080  o['variables']['node_install_corepack'] = b(not options.without_corepack)
1081  o['variables']['debug_node'] = b(options.debug_node)
1082  o['default_configuration'] = 'Debug' if options.debug else 'Release'
1083  o['variables']['error_on_warn'] = b(options.error_on_warn)
1084
1085  host_arch = host_arch_win() if os.name == 'nt' else host_arch_cc()
1086  target_arch = options.dest_cpu or host_arch
1087  # ia32 is preferred by the build tools (GYP) over x86 even if we prefer the latter
1088  # the Makefile resets this to x86 afterward
1089  if target_arch == 'x86':
1090    target_arch = 'ia32'
1091  # x86_64 is common across linuxes, allow it as an alias for x64
1092  if target_arch == 'x86_64':
1093    target_arch = 'x64'
1094  o['variables']['host_arch'] = host_arch
1095  o['variables']['target_arch'] = target_arch
1096  o['variables']['node_byteorder'] = sys.byteorder
1097
1098  cross_compiling = (options.cross_compiling
1099                     if options.cross_compiling is not None
1100                     else target_arch != host_arch)
1101  if cross_compiling:
1102    os.environ['GYP_CROSSCOMPILE'] = "1"
1103  if options.unused_without_snapshot:
1104    warn('building --without-snapshot is no longer possible')
1105
1106  o['variables']['want_separate_host_toolset'] = int(cross_compiling)
1107
1108  if options.without_node_snapshot or options.node_builtin_modules_path:
1109    o['variables']['node_use_node_snapshot'] = 'false'
1110  else:
1111    o['variables']['node_use_node_snapshot'] = b(
1112      not cross_compiling and not options.shared)
1113
1114  if options.without_node_code_cache or options.node_builtin_modules_path:
1115    o['variables']['node_use_node_code_cache'] = 'false'
1116  else:
1117    # TODO(refack): fix this when implementing embedded code-cache when cross-compiling.
1118    o['variables']['node_use_node_code_cache'] = b(
1119      not cross_compiling and not options.shared)
1120
1121  if target_arch == 'arm':
1122    configure_arm(o)
1123  elif target_arch in ('mips', 'mipsel', 'mips64el'):
1124    configure_mips(o, target_arch)
1125
1126  if flavor == 'aix':
1127    o['variables']['node_target_type'] = 'static_library'
1128
1129  if flavor != 'linux' and (options.enable_pgo_generate or options.enable_pgo_use):
1130    raise Exception(
1131      'The pgo option is supported only on linux.')
1132
1133  if flavor == 'linux':
1134    if options.enable_pgo_generate or options.enable_pgo_use:
1135      version_checked = (5, 4, 1)
1136      if not gcc_version_ge(version_checked):
1137        version_checked_str = ".".join(map(str, version_checked))
1138        raise Exception(
1139          'The options --enable-pgo-generate and --enable-pgo-use '
1140          'are supported for gcc and gxx %s or newer only.' % (version_checked_str))
1141
1142    if options.enable_pgo_generate and options.enable_pgo_use:
1143      raise Exception(
1144        'Only one of the --enable-pgo-generate or --enable-pgo-use options '
1145        'can be specified at a time. You would like to use '
1146        '--enable-pgo-generate first, profile node, and then recompile '
1147        'with --enable-pgo-use')
1148
1149  o['variables']['enable_pgo_generate'] = b(options.enable_pgo_generate)
1150  o['variables']['enable_pgo_use']      = b(options.enable_pgo_use)
1151
1152  if flavor == 'win' and (options.enable_lto):
1153    raise Exception(
1154      'Use Link Time Code Generation instead.')
1155
1156  if options.enable_lto:
1157    gcc_version_checked = (5, 4, 1)
1158    clang_version_checked = (3, 9, 1)
1159    if not gcc_version_ge(gcc_version_checked) and not clang_version_ge(clang_version_checked):
1160      gcc_version_checked_str = ".".join(map(str, gcc_version_checked))
1161      clang_version_checked_str = ".".join(map(str, clang_version_checked))
1162      raise Exception(
1163        'The option --enable-lto is supported for gcc %s+'
1164        'or clang %s+ only.' % (gcc_version_checked_str, clang_version_checked_str))
1165
1166  o['variables']['enable_lto'] = b(options.enable_lto)
1167
1168  if flavor in ('solaris', 'mac', 'linux', 'freebsd'):
1169    use_dtrace = not options.without_dtrace
1170    # Don't enable by default on linux and freebsd
1171    if flavor in ('linux', 'freebsd'):
1172      use_dtrace = options.with_dtrace
1173
1174    if flavor == 'linux':
1175      if options.systemtap_includes:
1176        o['include_dirs'] += [options.systemtap_includes]
1177    o['variables']['node_use_dtrace'] = b(use_dtrace)
1178  elif options.with_dtrace:
1179    raise Exception(
1180       'DTrace is currently only supported on SunOS, MacOS or Linux systems.')
1181  else:
1182    o['variables']['node_use_dtrace'] = 'false'
1183
1184  if options.node_use_large_pages or options.node_use_large_pages_script_lld:
1185    warn('''The `--use-largepages` and `--use-largepages-script-lld` options
1186         have no effect during build time. Support for mapping to large pages is
1187         now a runtime option of Node.js. Run `node --use-largepages` or add
1188         `--use-largepages` to the `NODE_OPTIONS` environment variable once
1189         Node.js is built to enable mapping to large pages.''')
1190
1191  if options.no_ifaddrs:
1192    o['defines'] += ['SUNOS_NO_IFADDRS']
1193
1194  # By default, enable ETW on Windows.
1195  if flavor == 'win':
1196    o['variables']['node_use_etw'] = b(not options.without_etw)
1197  elif options.with_etw:
1198    raise Exception('ETW is only supported on Windows.')
1199  else:
1200    o['variables']['node_use_etw'] = 'false'
1201
1202  o['variables']['node_with_ltcg'] = b(options.with_ltcg)
1203  if flavor != 'win' and options.with_ltcg:
1204    raise Exception('Link Time Code Generation is only supported on Windows.')
1205
1206  if options.tag:
1207    o['variables']['node_tag'] = '-' + options.tag
1208  else:
1209    o['variables']['node_tag'] = ''
1210
1211  o['variables']['node_release_urlbase'] = options.release_urlbase or ''
1212
1213  if options.v8_options:
1214    o['variables']['node_v8_options'] = options.v8_options.replace('"', '\\"')
1215
1216  if options.enable_static:
1217    o['variables']['node_target_type'] = 'static_library'
1218
1219  o['variables']['node_debug_lib'] = b(options.node_debug_lib)
1220
1221  if options.debug_nghttp2:
1222    o['variables']['debug_nghttp2'] = 1
1223  else:
1224    o['variables']['debug_nghttp2'] = 'false'
1225
1226  o['variables']['node_no_browser_globals'] = b(options.no_browser_globals)
1227
1228  o['variables']['node_shared'] = b(options.shared)
1229  node_module_version = getmoduleversion.get_version()
1230
1231  if options.dest_os == 'android':
1232    shlib_suffix = 'so'
1233  elif sys.platform == 'darwin':
1234    shlib_suffix = '%s.dylib'
1235  elif sys.platform.startswith('aix'):
1236    shlib_suffix = '%s.a'
1237  else:
1238    shlib_suffix = 'so.%s'
1239  if '%s' in shlib_suffix:
1240    shlib_suffix %= node_module_version
1241
1242  o['variables']['node_module_version'] = int(node_module_version)
1243  o['variables']['shlib_suffix'] = shlib_suffix
1244
1245  if options.linked_module:
1246    o['variables']['library_files'] = options.linked_module
1247
1248  o['variables']['asan'] = int(options.enable_asan or 0)
1249
1250  if options.coverage:
1251    o['variables']['coverage'] = 'true'
1252  else:
1253    o['variables']['coverage'] = 'false'
1254
1255  if options.shared:
1256    o['variables']['node_target_type'] = 'shared_library'
1257  elif options.enable_static:
1258    o['variables']['node_target_type'] = 'static_library'
1259  else:
1260    o['variables']['node_target_type'] = 'executable'
1261
1262  if options.node_builtin_modules_path:
1263    print('Warning! Loading builtin modules from disk is for development')
1264    o['variables']['node_builtin_modules_path'] = options.node_builtin_modules_path
1265
1266def configure_napi(output):
1267  version = getnapibuildversion.get_napi_version()
1268  output['variables']['napi_build_version'] = version
1269
1270def configure_library(lib, output, pkgname=None):
1271  shared_lib = 'shared_' + lib
1272  output['variables']['node_' + shared_lib] = b(getattr(options, shared_lib))
1273
1274  if getattr(options, shared_lib):
1275    (pkg_libs, pkg_cflags, pkg_libpath, _) = pkg_config(pkgname or lib)
1276
1277    if options.__dict__[shared_lib + '_includes']:
1278      output['include_dirs'] += [options.__dict__[shared_lib + '_includes']]
1279    elif pkg_cflags:
1280      stripped_flags = [flag.strip() for flag in pkg_cflags.split('-I')]
1281      output['include_dirs'] += [flag for flag in stripped_flags if flag]
1282
1283    # libpath needs to be provided ahead libraries
1284    if options.__dict__[shared_lib + '_libpath']:
1285      if flavor == 'win':
1286        if 'msvs_settings' not in output:
1287          output['msvs_settings'] = { 'VCLinkerTool': { 'AdditionalOptions': [] } }
1288        output['msvs_settings']['VCLinkerTool']['AdditionalOptions'] += [
1289          '/LIBPATH:%s' % options.__dict__[shared_lib + '_libpath']]
1290      else:
1291        output['libraries'] += [
1292            '-L%s' % options.__dict__[shared_lib + '_libpath']]
1293    elif pkg_libpath:
1294      output['libraries'] += [pkg_libpath]
1295
1296    default_libs = getattr(options, shared_lib + '_libname')
1297    default_libs = ['-l{0}'.format(l) for l in default_libs.split(',')]
1298
1299    if default_libs:
1300      output['libraries'] += default_libs
1301    elif pkg_libs:
1302      output['libraries'] += pkg_libs.split()
1303
1304
1305def configure_v8(o):
1306  o['variables']['v8_enable_lite_mode'] = 1 if options.v8_lite_mode else 0
1307  o['variables']['v8_enable_gdbjit'] = 1 if options.gdb else 0
1308  o['variables']['v8_no_strict_aliasing'] = 1  # Work around compiler bugs.
1309  o['variables']['v8_optimized_debug'] = 0 if options.v8_non_optimized_debug else 1
1310  o['variables']['dcheck_always_on'] = 1 if options.v8_with_dchecks else 0
1311  o['variables']['v8_enable_object_print'] = 1 if options.v8_enable_object_print else 0
1312  o['variables']['v8_random_seed'] = 0  # Use a random seed for hash tables.
1313  o['variables']['v8_promise_internal_field_count'] = 1 # Add internal field to promises for async hooks.
1314  o['variables']['v8_use_siphash'] = 0 if options.without_siphash else 1
1315  o['variables']['v8_enable_pointer_compression'] = 1 if options.enable_pointer_compression else 0
1316  o['variables']['v8_enable_31bit_smis_on_64bit_arch'] = 1 if options.enable_pointer_compression else 0
1317  o['variables']['v8_trace_maps'] = 1 if options.trace_maps else 0
1318  o['variables']['node_use_v8_platform'] = b(not options.without_v8_platform)
1319  o['variables']['node_use_bundled_v8'] = b(not options.without_bundled_v8)
1320  o['variables']['force_dynamic_crt'] = 1 if options.shared else 0
1321  o['variables']['node_enable_d8'] = b(options.enable_d8)
1322  if options.enable_d8:
1323    o['variables']['test_isolation_mode'] = 'noop'  # Needed by d8.gyp.
1324  if options.without_bundled_v8 and options.enable_d8:
1325    raise Exception('--enable-d8 is incompatible with --without-bundled-v8.')
1326  if options.without_bundled_v8 and options.build_v8_with_gn:
1327    raise Exception(
1328        '--build-v8-with-gn is incompatible with --without-bundled-v8.')
1329  if options.build_v8_with_gn:
1330    v8_path = os.path.join('deps', 'v8')
1331    print('Fetching dependencies to build V8 with GN')
1332    options.build_v8_with_gn = FetchDeps(v8_path)
1333  o['variables']['build_v8_with_gn'] = b(options.build_v8_with_gn)
1334
1335
1336def configure_openssl(o):
1337  variables = o['variables']
1338  variables['node_use_openssl'] = b(not options.without_ssl)
1339  variables['node_shared_openssl'] = b(options.shared_openssl)
1340  variables['openssl_is_fips'] = b(options.openssl_is_fips)
1341  variables['openssl_fips'] = ''
1342
1343  if options.openssl_no_asm:
1344    variables['openssl_no_asm'] = 1
1345
1346  o['defines'] += ['NODE_OPENSSL_CONF_NAME=' + options.openssl_conf_name]
1347
1348  if options.without_ssl:
1349    def without_ssl_error(option):
1350      error('--without-ssl is incompatible with %s' % option)
1351    if options.shared_openssl:
1352      without_ssl_error('--shared-openssl')
1353    if options.openssl_no_asm:
1354      without_ssl_error('--openssl-no-asm')
1355    if options.openssl_fips:
1356      without_ssl_error('--openssl-fips')
1357    if options.openssl_default_cipher_list:
1358      without_ssl_error('--openssl-default-cipher-list')
1359    return
1360
1361  if options.use_openssl_ca_store:
1362    o['defines'] += ['NODE_OPENSSL_CERT_STORE']
1363  if options.openssl_system_ca_path:
1364    variables['openssl_system_ca_path'] = options.openssl_system_ca_path
1365  variables['node_without_node_options'] = b(options.without_node_options)
1366  if options.without_node_options:
1367      o['defines'] += ['NODE_WITHOUT_NODE_OPTIONS']
1368  if options.openssl_default_cipher_list:
1369    variables['openssl_default_cipher_list'] = \
1370            options.openssl_default_cipher_list
1371
1372  if not options.shared_openssl and not options.openssl_no_asm:
1373    is_x86 = 'x64' in variables['target_arch'] or 'ia32' in variables['target_arch']
1374
1375    # supported asm compiler for AVX2. See https://github.com/openssl/openssl/
1376    # blob/OpenSSL_1_1_0-stable/crypto/modes/asm/aesni-gcm-x86_64.pl#L52-L69
1377    openssl110_asm_supported = \
1378      ('gas_version' in variables and StrictVersion(variables['gas_version']) >= StrictVersion('2.23')) or \
1379      ('xcode_version' in variables and StrictVersion(variables['xcode_version']) >= StrictVersion('5.0')) or \
1380      ('llvm_version' in variables and StrictVersion(variables['llvm_version']) >= StrictVersion('3.3')) or \
1381      ('nasm_version' in variables and StrictVersion(variables['nasm_version']) >= StrictVersion('2.10'))
1382
1383    if is_x86 and not openssl110_asm_supported:
1384      error('''Did not find a new enough assembler, install one or build with
1385       --openssl-no-asm.
1386       Please refer to BUILDING.md''')
1387
1388  elif options.openssl_no_asm:
1389    warn('''--openssl-no-asm will result in binaries that do not take advantage
1390         of modern CPU cryptographic instructions and will therefore be slower.
1391         Please refer to BUILDING.md''')
1392
1393  if options.openssl_no_asm and options.shared_openssl:
1394    error('--openssl-no-asm is incompatible with --shared-openssl')
1395
1396  if options.openssl_fips or options.openssl_fips == '':
1397     error('FIPS is not supported in this version of Node.js')
1398
1399  configure_library('openssl', o)
1400
1401
1402def configure_static(o):
1403  if options.fully_static or options.partly_static:
1404    if flavor == 'mac':
1405      warn("Generation of static executable will not work on OSX "
1406            "when using the default compilation environment")
1407      return
1408
1409    if options.fully_static:
1410      o['libraries'] += ['-static']
1411    elif options.partly_static:
1412      o['libraries'] += ['-static-libgcc', '-static-libstdc++']
1413      if options.enable_asan:
1414        o['libraries'] += ['-static-libasan']
1415
1416
1417def write(filename, data):
1418  print_verbose('creating %s' % filename)
1419  with open(filename, 'w+') as f:
1420    f.write(data)
1421
1422do_not_edit = '# Do not edit. Generated by the configure script.\n'
1423
1424def glob_to_var(dir_base, dir_sub, patch_dir):
1425  list = []
1426  dir_all = '%s/%s' % (dir_base, dir_sub)
1427  files = os.walk(dir_all)
1428  for ent in files:
1429    (path, dirs, files) = ent
1430    for file in files:
1431      if file.endswith('.cpp') or file.endswith('.c') or file.endswith('.h'):
1432        # srcfile uses "slash" as dir separator as its output is consumed by gyp
1433        srcfile = '%s/%s' % (dir_sub, file)
1434        if patch_dir:
1435          patchfile = '%s/%s/%s' % (dir_base, patch_dir, file)
1436          if os.path.isfile(patchfile):
1437            srcfile = '%s/%s' % (patch_dir, file)
1438            info('Using floating patch "%s" from "%s"' % (patchfile, dir_base))
1439        list.append(srcfile)
1440    break
1441  return list
1442
1443def configure_intl(o):
1444  def icu_download(path):
1445    depFile = 'tools/icu/current_ver.dep'
1446    with open(depFile) as f:
1447      icus = json.load(f)
1448    # download ICU, if needed
1449    if not os.access(options.download_path, os.W_OK):
1450      error('''Cannot write to desired download path.
1451        Either create it or verify permissions.''')
1452    attemptdownload = nodedownload.candownload(auto_downloads, "icu")
1453    for icu in icus:
1454      url = icu['url']
1455      (expectHash, hashAlgo, allAlgos) = nodedownload.findHash(icu)
1456      if not expectHash:
1457        error('''Could not find a hash to verify ICU download.
1458          %s may be incorrect.
1459          For the entry %s,
1460          Expected one of these keys: %s''' % (depFile, url, ' '.join(allAlgos)))
1461      local = url.split('/')[-1]
1462      targetfile = os.path.join(options.download_path, local)
1463      if not os.path.isfile(targetfile):
1464        if attemptdownload:
1465          nodedownload.retrievefile(url, targetfile)
1466      else:
1467        print('Re-using existing %s' % targetfile)
1468      if os.path.isfile(targetfile):
1469        print('Checking file integrity with %s:\r' % hashAlgo)
1470        gotHash = nodedownload.checkHash(targetfile, hashAlgo)
1471        print('%s:      %s  %s' % (hashAlgo, gotHash, targetfile))
1472        if (expectHash == gotHash):
1473          return targetfile
1474        else:
1475          warn('Expected: %s      *MISMATCH*' % expectHash)
1476          warn('\n ** Corrupted ZIP? Delete %s to retry download.\n' % targetfile)
1477    return None
1478  icu_config = {
1479    'variables': {}
1480  }
1481  icu_config_name = 'icu_config.gypi'
1482
1483  # write an empty file to start with
1484  write(icu_config_name, do_not_edit +
1485        pprint.pformat(icu_config, indent=2) + '\n')
1486
1487  # always set icu_small, node.gyp depends on it being defined.
1488  o['variables']['icu_small'] = b(False)
1489
1490  with_intl = options.with_intl
1491  with_icu_source = options.with_icu_source
1492  have_icu_path = bool(options.with_icu_path)
1493  if have_icu_path and with_intl != 'none':
1494    error('Cannot specify both --with-icu-path and --with-intl')
1495  elif have_icu_path:
1496    # Chromium .gyp mode: --with-icu-path
1497    o['variables']['v8_enable_i18n_support'] = 1
1498    # use the .gyp given
1499    o['variables']['icu_gyp_path'] = options.with_icu_path
1500    return
1501  # --with-intl=<with_intl>
1502  # set the default
1503  if with_intl in (None, 'none'):
1504    o['variables']['v8_enable_i18n_support'] = 0
1505    return  # no Intl
1506  elif with_intl == 'small-icu':
1507    # small ICU (English only)
1508    o['variables']['v8_enable_i18n_support'] = 1
1509    o['variables']['icu_small'] = b(True)
1510    locs = set(options.with_icu_locales.split(','))
1511    locs.add('root')  # must have root
1512    o['variables']['icu_locales'] = ','.join(str(loc) for loc in locs)
1513    # We will check a bit later if we can use the canned deps/icu-small
1514    o['variables']['icu_default_data'] = options.with_icu_default_data_dir or ''
1515  elif with_intl == 'full-icu':
1516    # full ICU
1517    o['variables']['v8_enable_i18n_support'] = 1
1518  elif with_intl == 'system-icu':
1519    # ICU from pkg-config.
1520    o['variables']['v8_enable_i18n_support'] = 1
1521    pkgicu = pkg_config('icu-i18n')
1522    if not pkgicu[0]:
1523      error('''Could not load pkg-config data for "icu-i18n".
1524       See above errors or the README.md.''')
1525    (libs, cflags, libpath, icuversion) = pkgicu
1526    icu_ver_major = icuversion.split('.')[0]
1527    o['variables']['icu_ver_major'] = icu_ver_major
1528    if int(icu_ver_major) < icu_versions['minimum_icu']:
1529      error('icu4c v%s is too old, v%d.x or later is required.' %
1530            (icuversion, icu_versions['minimum_icu']))
1531    # libpath provides linker path which may contain spaces
1532    if libpath:
1533      o['libraries'] += [libpath]
1534    # safe to split, cannot contain spaces
1535    o['libraries'] += libs.split()
1536    if cflags:
1537      stripped_flags = [flag.strip() for flag in cflags.split('-I')]
1538      o['include_dirs'] += [flag for flag in stripped_flags if flag]
1539    # use the "system" .gyp
1540    o['variables']['icu_gyp_path'] = 'tools/icu/icu-system.gyp'
1541    return
1542
1543  # this is just the 'deps' dir. Used for unpacking.
1544  icu_parent_path = 'deps'
1545
1546  # The full path to the ICU source directory. Should not include './'.
1547  icu_deps_path = 'deps/icu'
1548  icu_full_path = icu_deps_path
1549
1550  # icu-tmp is used to download and unpack the ICU tarball.
1551  icu_tmp_path = os.path.join(icu_parent_path, 'icu-tmp')
1552
1553  # canned ICU. see tools/icu/README.md to update.
1554  canned_icu_dir = 'deps/icu-small'
1555
1556  # use the README to verify what the canned ICU is
1557  canned_is_full = os.path.isfile(os.path.join(canned_icu_dir, 'README-FULL-ICU.txt'))
1558  canned_is_small = os.path.isfile(os.path.join(canned_icu_dir, 'README-SMALL-ICU.txt'))
1559  if canned_is_small:
1560    warn('Ignoring %s - in-repo small icu is no longer supported.' % canned_icu_dir)
1561
1562  # We can use 'deps/icu-small' - pre-canned ICU *iff*
1563  # - canned_is_full AND
1564  # - with_icu_source is unset (i.e. no other ICU was specified)
1565  #
1566  # This is *roughly* equivalent to
1567  # $ configure --with-intl=full-icu --with-icu-source=deps/icu-small
1568  # .. Except that we avoid copying icu-small over to deps/icu.
1569  # In this default case, deps/icu is ignored, although make clean will
1570  # still harmlessly remove deps/icu.
1571
1572  if (not with_icu_source) and canned_is_full:
1573    # OK- we can use the canned ICU.
1574    icu_full_path = canned_icu_dir
1575    icu_config['variables']['icu_full_canned'] = 1
1576  # --with-icu-source processing
1577  # now, check that they didn't pass --with-icu-source=deps/icu
1578  elif with_icu_source and os.path.abspath(icu_full_path) == os.path.abspath(with_icu_source):
1579    warn('Ignoring redundant --with-icu-source=%s' % with_icu_source)
1580    with_icu_source = None
1581  # if with_icu_source is still set, try to use it.
1582  if with_icu_source:
1583    if os.path.isdir(icu_full_path):
1584      print('Deleting old ICU source: %s' % icu_full_path)
1585      shutil.rmtree(icu_full_path)
1586    # now, what path was given?
1587    if os.path.isdir(with_icu_source):
1588      # it's a path. Copy it.
1589      print('%s -> %s' % (with_icu_source, icu_full_path))
1590      shutil.copytree(with_icu_source, icu_full_path)
1591    else:
1592      # could be file or URL.
1593      # Set up temporary area
1594      if os.path.isdir(icu_tmp_path):
1595        shutil.rmtree(icu_tmp_path)
1596      os.mkdir(icu_tmp_path)
1597      icu_tarball = None
1598      if os.path.isfile(with_icu_source):
1599        # it's a file. Try to unpack it.
1600        icu_tarball = with_icu_source
1601      else:
1602        # Can we download it?
1603        local = os.path.join(icu_tmp_path, with_icu_source.split('/')[-1])  # local part
1604        icu_tarball = nodedownload.retrievefile(with_icu_source, local)
1605      # continue with "icu_tarball"
1606      nodedownload.unpack(icu_tarball, icu_tmp_path)
1607      # Did it unpack correctly? Should contain 'icu'
1608      tmp_icu = os.path.join(icu_tmp_path, 'icu')
1609      if os.path.isdir(tmp_icu):
1610        os.rename(tmp_icu, icu_full_path)
1611        shutil.rmtree(icu_tmp_path)
1612      else:
1613        shutil.rmtree(icu_tmp_path)
1614        error('--with-icu-source=%s did not result in an "icu" dir.' % \
1615               with_icu_source)
1616
1617  # ICU mode. (icu-generic.gyp)
1618  o['variables']['icu_gyp_path'] = 'tools/icu/icu-generic.gyp'
1619  # ICU source dir relative to tools/icu (for .gyp file)
1620  o['variables']['icu_path'] = icu_full_path
1621  if not os.path.isdir(icu_full_path):
1622    # can we download (or find) a zipfile?
1623    localzip = icu_download(icu_full_path)
1624    if localzip:
1625      nodedownload.unpack(localzip, icu_parent_path)
1626    else:
1627      warn('* ECMA-402 (Intl) support didn\'t find ICU in %s..' % icu_full_path)
1628  if not os.path.isdir(icu_full_path):
1629    error('''Cannot build Intl without ICU in %s.
1630       Fix, or disable with "--with-intl=none"''' % icu_full_path)
1631  else:
1632    print_verbose('* Using ICU in %s' % icu_full_path)
1633  # Now, what version of ICU is it? We just need the "major", such as 54.
1634  # uvernum.h contains it as a #define.
1635  uvernum_h = os.path.join(icu_full_path, 'source/common/unicode/uvernum.h')
1636  if not os.path.isfile(uvernum_h):
1637    error('Could not load %s - is ICU installed?' % uvernum_h)
1638  icu_ver_major = None
1639  matchVerExp = r'^\s*#define\s+U_ICU_VERSION_SHORT\s+"([^"]*)".*'
1640  match_version = re.compile(matchVerExp)
1641  with io.open(uvernum_h, encoding='utf8') as in_file:
1642    for line in in_file:
1643      m = match_version.match(line)
1644      if m:
1645        icu_ver_major = str(m.group(1))
1646  if not icu_ver_major:
1647    error('Could not read U_ICU_VERSION_SHORT version from %s' % uvernum_h)
1648  elif int(icu_ver_major) < icu_versions['minimum_icu']:
1649    error('icu4c v%s.x is too old, v%d.x or later is required.' %
1650          (icu_ver_major, icu_versions['minimum_icu']))
1651  icu_endianness = sys.byteorder[0]
1652  o['variables']['icu_ver_major'] = icu_ver_major
1653  o['variables']['icu_endianness'] = icu_endianness
1654  icu_data_file_l = 'icudt%s%s.dat' % (icu_ver_major, 'l') # LE filename
1655  icu_data_file = 'icudt%s%s.dat' % (icu_ver_major, icu_endianness)
1656  # relative to configure
1657  icu_data_path = os.path.join(icu_full_path,
1658                               'source/data/in',
1659                               icu_data_file_l) # LE
1660  compressed_data = '%s.bz2' % (icu_data_path)
1661  if not os.path.isfile(icu_data_path) and os.path.isfile(compressed_data):
1662    # unpack. deps/icu is a temporary path
1663    if os.path.isdir(icu_tmp_path):
1664      shutil.rmtree(icu_tmp_path)
1665    os.mkdir(icu_tmp_path)
1666    icu_data_path = os.path.join(icu_tmp_path, icu_data_file_l)
1667    with open(icu_data_path, 'wb') as outf:
1668        inf = bz2.BZ2File(compressed_data, 'rb')
1669        try:
1670          shutil.copyfileobj(inf, outf)
1671        finally:
1672          inf.close()
1673    # Now, proceed..
1674
1675  # relative to dep..
1676  icu_data_in = os.path.join('..','..', icu_data_path)
1677  if not os.path.isfile(icu_data_path) and icu_endianness != 'l':
1678    # use host endianness
1679    icu_data_path = os.path.join(icu_full_path,
1680                                 'source/data/in',
1681                                 icu_data_file) # will be generated
1682  if not os.path.isfile(icu_data_path):
1683    # .. and we're not about to build it from .gyp!
1684    error('''ICU prebuilt data file %s does not exist.
1685       See the README.md.''' % icu_data_path)
1686
1687  # this is the input '.dat' file to use .. icudt*.dat
1688  # may be little-endian if from a icu-project.org tarball
1689  o['variables']['icu_data_in'] = icu_data_in
1690
1691  # map from variable name to subdirs
1692  icu_src = {
1693    'stubdata': 'stubdata',
1694    'common': 'common',
1695    'i18n': 'i18n',
1696    'tools': 'tools/toolutil',
1697    'genccode': 'tools/genccode',
1698    'genrb': 'tools/genrb',
1699    'icupkg': 'tools/icupkg',
1700  }
1701  # this creates a variable icu_src_XXX for each of the subdirs
1702  # with a list of the src files to use
1703  for i in icu_src:
1704    var  = 'icu_src_%s' % i
1705    path = '../../%s/source/%s' % (icu_full_path, icu_src[i])
1706    icu_config['variables'][var] = glob_to_var('tools/icu', path, 'patches/%s/source/%s' % (icu_ver_major, icu_src[i]) )
1707  # calculate platform-specific genccode args
1708  # print("platform %s, flavor %s" % (sys.platform, flavor))
1709  # if sys.platform == 'darwin':
1710  #   shlib_suffix = '%s.dylib'
1711  # elif sys.platform.startswith('aix'):
1712  #   shlib_suffix = '%s.a'
1713  # else:
1714  #   shlib_suffix = 'so.%s'
1715  if flavor == 'win':
1716    icu_config['variables']['icu_asm_ext'] = 'obj'
1717    icu_config['variables']['icu_asm_opts'] = [ '-o ' ]
1718  elif with_intl == 'small-icu' or options.cross_compiling:
1719    icu_config['variables']['icu_asm_ext'] = 'c'
1720    icu_config['variables']['icu_asm_opts'] = []
1721  elif flavor == 'mac':
1722    icu_config['variables']['icu_asm_ext'] = 'S'
1723    icu_config['variables']['icu_asm_opts'] = [ '-a', 'gcc-darwin' ]
1724  elif sys.platform.startswith('aix'):
1725    icu_config['variables']['icu_asm_ext'] = 'S'
1726    icu_config['variables']['icu_asm_opts'] = [ '-a', 'xlc' ]
1727  else:
1728    # assume GCC-compatible asm is OK
1729    icu_config['variables']['icu_asm_ext'] = 'S'
1730    icu_config['variables']['icu_asm_opts'] = [ '-a', 'gcc' ]
1731
1732  # write updated icu_config.gypi with a bunch of paths
1733  write(icu_config_name, do_not_edit +
1734        pprint.pformat(icu_config, indent=2) + '\n')
1735  return  # end of configure_intl
1736
1737def configure_inspector(o):
1738  disable_inspector = (options.without_inspector or
1739                       options.with_intl in (None, 'none') or
1740                       options.without_ssl)
1741  o['variables']['v8_enable_inspector'] = 0 if disable_inspector else 1
1742
1743def configure_section_file(o):
1744  try:
1745    proc = subprocess.Popen(['ld.gold'] + ['-v'], stdin = subprocess.PIPE,
1746                            stdout = subprocess.PIPE, stderr = subprocess.PIPE)
1747  except OSError:
1748    if options.node_section_ordering_info != "":
1749      warn('''No acceptable ld.gold linker found!''')
1750    return 0
1751
1752  match = re.match(r"^GNU gold.*([0-9]+)\.([0-9]+)$",
1753                   proc.communicate()[0].decode("utf-8"))
1754
1755  if match:
1756    gold_major_version = match.group(1)
1757    gold_minor_version = match.group(2)
1758    if int(gold_major_version) == 1 and int(gold_minor_version) <= 1:
1759      error('''GNU gold version must be greater than 1.2 in order to use section
1760            reordering''')
1761
1762  if options.node_section_ordering_info != "":
1763    o['variables']['node_section_ordering_info'] = os.path.realpath(
1764      str(options.node_section_ordering_info))
1765  else:
1766    o['variables']['node_section_ordering_info'] = ""
1767
1768def make_bin_override():
1769  if sys.platform == 'win32':
1770    raise Exception('make_bin_override should not be called on win32.')
1771  # If the system python is not the python we are running (which should be
1772  # python 2), then create a directory with a symlink called `python` to our
1773  # sys.executable. This directory will be prefixed to the PATH, so that
1774  # other tools that shell out to `python` will use the appropriate python
1775
1776  which_python = which('python')
1777  if (which_python and
1778      os.path.realpath(which_python) == os.path.realpath(sys.executable)):
1779    return
1780
1781  bin_override = os.path.abspath('out/tools/bin')
1782  try:
1783    os.makedirs(bin_override)
1784  except OSError as e:
1785    if e.errno != errno.EEXIST: raise e
1786
1787  python_link = os.path.join(bin_override, 'python')
1788  try:
1789    os.unlink(python_link)
1790  except OSError as e:
1791    if e.errno != errno.ENOENT: raise e
1792  os.symlink(sys.executable, python_link)
1793
1794  # We need to set the environment right now so that when gyp (in run_gyp)
1795  # shells out, it finds the right python (specifically at
1796  # https://github.com/nodejs/node/blob/d82e107/deps/v8/gypfiles/toolchain.gypi#L43)
1797  os.environ['PATH'] = bin_override + ':' + os.environ['PATH']
1798
1799  return bin_override
1800
1801output = {
1802  'variables': {},
1803  'include_dirs': [],
1804  'libraries': [],
1805  'defines': [],
1806  'cflags': [],
1807}
1808
1809# Print a warning when the compiler is too old.
1810check_compiler(output)
1811
1812# determine the "flavor" (operating system) we're building for,
1813# leveraging gyp's GetFlavor function
1814flavor_params = {}
1815if (options.dest_os):
1816  flavor_params['flavor'] = options.dest_os
1817flavor = GetFlavor(flavor_params)
1818
1819configure_node(output)
1820configure_node_lib_files(output)
1821configure_napi(output)
1822configure_library('zlib', output)
1823configure_library('http_parser', output)
1824configure_library('libuv', output)
1825configure_library('brotli', output, pkgname=['libbrotlidec', 'libbrotlienc'])
1826configure_library('cares', output, pkgname='libcares')
1827configure_library('nghttp2', output, pkgname='libnghttp2')
1828configure_v8(output)
1829configure_openssl(output)
1830configure_intl(output)
1831configure_static(output)
1832configure_inspector(output)
1833configure_section_file(output)
1834
1835# Forward OSS-Fuzz settings
1836output['variables']['ossfuzz'] = b(options.ossfuzz)
1837
1838# variables should be a root level element,
1839# move everything else to target_defaults
1840variables = output['variables']
1841del output['variables']
1842variables['is_debug'] = B(options.debug)
1843
1844# make_global_settings for special FIPS linking
1845# should not be used to compile modules in node-gyp
1846config_fips = { 'make_global_settings' : [] }
1847if 'make_fips_settings' in output:
1848  config_fips['make_global_settings'] = output['make_fips_settings']
1849  del output['make_fips_settings']
1850  write('config_fips.gypi', do_not_edit +
1851        pprint.pformat(config_fips, indent=2) + '\n')
1852
1853# make_global_settings should be a root level element too
1854if 'make_global_settings' in output:
1855  make_global_settings = output['make_global_settings']
1856  del output['make_global_settings']
1857else:
1858  make_global_settings = False
1859
1860output = {
1861  'variables': variables,
1862  'target_defaults': output,
1863}
1864if make_global_settings:
1865  output['make_global_settings'] = make_global_settings
1866
1867print_verbose(output)
1868
1869write('config.gypi', do_not_edit +
1870      pprint.pformat(output, indent=2) + '\n')
1871
1872write('config.status', '#!/bin/sh\nset -x\nexec ./configure ' +
1873      ' '.join([pipes.quote(arg) for arg in original_argv]) + '\n')
1874os.chmod('config.status', 0o775)
1875
1876
1877config = {
1878  'BUILDTYPE': 'Debug' if options.debug else 'Release',
1879  'NODE_TARGET_TYPE': variables['node_target_type'],
1880}
1881
1882# Not needed for trivial case. Useless when it's a win32 path.
1883if sys.executable != 'python' and ':\\' not in sys.executable:
1884  config['PYTHON'] = sys.executable
1885
1886if options.prefix:
1887  config['PREFIX'] = options.prefix
1888
1889if options.use_ninja:
1890  config['BUILD_WITH'] = 'ninja'
1891
1892# On Windows there is another find.exe in C:\Windows\System32
1893if sys.platform == 'win32':
1894  config['FIND'] = '/usr/bin/find'
1895
1896config_lines = ['='.join((k,v)) for k,v in config.items()]
1897# Add a blank string to get a blank line at the end.
1898config_lines += ['']
1899config_str = '\n'.join(config_lines)
1900
1901# On Windows there's no reason to search for a different python binary.
1902bin_override = None if sys.platform == 'win32' else make_bin_override()
1903if bin_override:
1904  config_str = 'export PATH:=' + bin_override + ':$(PATH)\n' + config_str
1905
1906write('config.mk', do_not_edit + config_str)
1907
1908
1909
1910gyp_args = ['--no-parallel', '-Dconfiguring_node=1']
1911
1912if options.use_ninja:
1913  gyp_args += ['-f', 'ninja']
1914elif flavor == 'win' and sys.platform != 'msys':
1915  gyp_args += ['-f', 'msvs', '-G', 'msvs_version=auto']
1916else:
1917  gyp_args += ['-f', 'make-' + flavor]
1918
1919if options.compile_commands_json:
1920  gyp_args += ['-f', 'compile_commands_json']
1921
1922# override the variable `python` defined in common.gypi
1923if bin_override is not None:
1924  gyp_args += ['-Dpython=' + sys.executable]
1925
1926# pass the leftover positional arguments to GYP
1927gyp_args += args
1928
1929if warn.warned and not options.verbose:
1930  warn('warnings were emitted in the configure phase')
1931
1932print_verbose("running: \n    " + " ".join(['python', 'tools/gyp_node.py'] + gyp_args))
1933run_gyp(gyp_args)
1934info('configure completed successfully')
1935