test: fix flaky child-process-fork-regr-gh-2847
[platform/upstream/nodejs.git] / configure
1 #!/usr/bin/env python
2 import optparse
3 import os
4 import pprint
5 import re
6 import shlex
7 import subprocess
8 import sys
9 import shutil
10 import string
11
12 # gcc and g++ as defaults matches what GYP's Makefile generator does,
13 # except on OS X.
14 CC = os.environ.get('CC', 'cc' if sys.platform == 'darwin' else 'gcc')
15 CXX = os.environ.get('CXX', 'c++' if sys.platform == 'darwin' else 'g++')
16
17 root_dir = os.path.dirname(__file__)
18 sys.path.insert(0, os.path.join(root_dir, 'tools', 'gyp', 'pylib'))
19 from gyp.common import GetFlavor
20
21 # imports in tools/configure.d
22 sys.path.insert(0, os.path.join(root_dir, 'tools', 'configure.d'))
23 import nodedownload
24
25 # parse our options
26 parser = optparse.OptionParser()
27
28 valid_os = ('win', 'mac', 'solaris', 'freebsd', 'openbsd', 'linux',
29             'android', 'aix')
30 valid_arch = ('arm', 'arm64', 'ia32', 'mips', 'mipsel', 'ppc', 'ppc64', 'x32',
31               'x64', 'x86')
32 valid_arm_float_abi = ('soft', 'softfp', 'hard')
33 valid_arm_fpu = ('vfp', 'vfpv3', 'vfpv3-d16', 'neon')
34 valid_mips_arch = ('loongson', 'r1', 'r2', 'r6', 'rx')
35 valid_mips_fpu = ('fp32', 'fp64', 'fpxx')
36 valid_mips_float_abi = ('soft', 'hard')
37 valid_intl_modes = ('none', 'small-icu', 'full-icu', 'system-icu')
38
39 # create option groups
40 shared_optgroup = optparse.OptionGroup(parser, "Shared libraries",
41     "Flags that allows you to control whether you want to build against "
42     "built-in dependencies or its shared representations. If necessary, "
43     "provide multiple libraries with comma.")
44 intl_optgroup = optparse.OptionGroup(parser, "Internationalization",
45     "Flags that lets you enable i18n features in Node.js as well as which "
46     "library you want to build against.")
47
48 # Options should be in alphabetical order but keep --prefix at the top,
49 # that's arguably the one people will be looking for most.
50 parser.add_option('--prefix',
51     action='store',
52     dest='prefix',
53     default='/usr/local',
54     help='select the install prefix [default: %default]')
55
56 parser.add_option('--debug',
57     action='store_true',
58     dest='debug',
59     help='also build debug build')
60
61 parser.add_option('--dest-cpu',
62     action='store',
63     dest='dest_cpu',
64     choices=valid_arch,
65     help='CPU architecture to build for ({0})'.format(', '.join(valid_arch)))
66
67 parser.add_option('--dest-os',
68     action='store',
69     dest='dest_os',
70     choices=valid_os,
71     help='operating system to build for ({0})'.format(', '.join(valid_os)))
72
73 parser.add_option('--gdb',
74     action='store_true',
75     dest='gdb',
76     help='add gdb support')
77
78 parser.add_option('--no-ifaddrs',
79     action='store_true',
80     dest='no_ifaddrs',
81     help='use on deprecated SunOS systems that do not support ifaddrs.h')
82
83 parser.add_option("--fully-static",
84     action="store_true",
85     dest="fully_static",
86     help="Generate an executable without external dynamic libraries. This "
87          "will not work on OSX when using the default compilation environment")
88
89 parser.add_option("--partly-static",
90     action="store_true",
91     dest="partly_static",
92     help="Generate an executable with libgcc and libstdc++ libraries. This "
93          "will not work on OSX when using the default compilation environment")
94
95 parser.add_option("--link-module",
96     action="append",
97     dest="linked_module",
98     help="Path to a JS file to be bundled in the binary as a builtin."
99          "This module will be referenced by path without extension."
100          "e.g. /root/x/y.js will be referenced via require('root/x/y')."
101          "Can be used multiple times")
102
103 parser.add_option("--openssl-no-asm",
104     action="store_true",
105     dest="openssl_no_asm",
106     help="Do not build optimized assembly for OpenSSL")
107
108 parser.add_option('--openssl-fips',
109     action='store',
110     dest='openssl_fips',
111     help='Build OpenSSL using FIPS canister .o file in supplied folder')
112
113 shared_optgroup.add_option('--shared-http-parser',
114     action='store_true',
115     dest='shared_http_parser',
116     help='link to a shared http_parser DLL instead of static linking')
117
118 shared_optgroup.add_option('--shared-http-parser-includes',
119     action='store',
120     dest='shared_http_parser_includes',
121     help='directory containing http_parser header files')
122
123 shared_optgroup.add_option('--shared-http-parser-libname',
124     action='store',
125     dest='shared_http_parser_libname',
126     default='http_parser',
127     help='alternative lib name to link to [default: %default]')
128
129 shared_optgroup.add_option('--shared-http-parser-libpath',
130     action='store',
131     dest='shared_http_parser_libpath',
132     help='a directory to search for the shared http_parser DLL')
133
134 shared_optgroup.add_option('--shared-libuv',
135     action='store_true',
136     dest='shared_libuv',
137     help='link to a shared libuv DLL instead of static linking')
138
139 shared_optgroup.add_option('--shared-libuv-includes',
140     action='store',
141     dest='shared_libuv_includes',
142     help='directory containing libuv header files')
143
144 shared_optgroup.add_option('--shared-libuv-libname',
145     action='store',
146     dest='shared_libuv_libname',
147     default='uv',
148     help='alternative lib name to link to [default: %default]')
149
150 shared_optgroup.add_option('--shared-libuv-libpath',
151     action='store',
152     dest='shared_libuv_libpath',
153     help='a directory to search for the shared libuv DLL')
154
155 shared_optgroup.add_option('--shared-openssl',
156     action='store_true',
157     dest='shared_openssl',
158     help='link to a shared OpenSSl DLL instead of static linking')
159
160 shared_optgroup.add_option('--shared-openssl-includes',
161     action='store',
162     dest='shared_openssl_includes',
163     help='directory containing OpenSSL header files')
164
165 shared_optgroup.add_option('--shared-openssl-libname',
166     action='store',
167     dest='shared_openssl_libname',
168     default='crypto,ssl',
169     help='alternative lib name to link to [default: %default]')
170
171 shared_optgroup.add_option('--shared-openssl-libpath',
172     action='store',
173     dest='shared_openssl_libpath',
174     help='a directory to search for the shared OpenSSL DLLs')
175
176 shared_optgroup.add_option('--shared-zlib',
177     action='store_true',
178     dest='shared_zlib',
179     help='link to a shared zlib DLL instead of static linking')
180
181 shared_optgroup.add_option('--shared-zlib-includes',
182     action='store',
183     dest='shared_zlib_includes',
184     help='directory containing zlib header files')
185
186 shared_optgroup.add_option('--shared-zlib-libname',
187     action='store',
188     dest='shared_zlib_libname',
189     default='z',
190     help='alternative lib name to link to [default: %default]')
191
192 shared_optgroup.add_option('--shared-zlib-libpath',
193     action='store',
194     dest='shared_zlib_libpath',
195     help='a directory to search for the shared zlib DLL')
196
197 parser.add_option_group(shared_optgroup)
198
199 parser.add_option('--systemtap-includes',
200     action='store',
201     dest='systemtap_includes',
202     help='directory containing systemtap header files')
203
204 parser.add_option('--tag',
205     action='store',
206     dest='tag',
207     help='custom build tag')
208
209 parser.add_option('--release-urlbase',
210     action='store',
211     dest='release_urlbase',
212     help='Provide a custom URL prefix for the `process.release` properties '
213          '`sourceUrl` and `headersUrl`. When compiling a release build, this '
214          'will default to https://nodejs.org/download/release/')
215
216 parser.add_option('--v8-options',
217     action='store',
218     dest='v8_options',
219     help='v8 options to pass, see `node --v8-options` for examples.')
220
221 parser.add_option('--with-arm-float-abi',
222     action='store',
223     dest='arm_float_abi',
224     choices=valid_arm_float_abi,
225     help='specifies which floating-point ABI to use ({0}).'.format(
226         ', '.join(valid_arm_float_abi)))
227
228 parser.add_option('--with-arm-fpu',
229     action='store',
230     dest='arm_fpu',
231     choices=valid_arm_fpu,
232     help='ARM FPU mode ({0}) [default: %default]'.format(
233         ', '.join(valid_arm_fpu)))
234
235 parser.add_option('--with-mips-arch-variant',
236     action='store',
237     dest='mips_arch_variant',
238     default='r2',
239     choices=valid_mips_arch,
240     help='MIPS arch variant ({0}) [default: %default]'.format(
241         ', '.join(valid_mips_arch)))
242
243 parser.add_option('--with-mips-fpu-mode',
244     action='store',
245     dest='mips_fpu_mode',
246     default='fp32',
247     choices=valid_mips_fpu,
248     help='MIPS FPU mode ({0}) [default: %default]'.format(
249         ', '.join(valid_mips_fpu)))
250
251 parser.add_option('--with-mips-float-abi',
252     action='store',
253     dest='mips_float_abi',
254     default='hard',
255     choices=valid_mips_float_abi,
256     help='MIPS floating-point ABI ({0}) [default: %default]'.format(
257         ', '.join(valid_mips_float_abi)))
258
259 parser.add_option('--with-dtrace',
260     action='store_true',
261     dest='with_dtrace',
262     help='build with DTrace (default is true on sunos and darwin)')
263
264 parser.add_option('--with-lttng',
265     action='store_true',
266     dest='with_lttng',
267     help='build with Lttng (Only available to Linux)')
268
269 parser.add_option('--with-etw',
270     action='store_true',
271     dest='with_etw',
272     help='build with ETW (default is true on Windows)')
273
274 intl_optgroup.add_option('--with-intl',
275     action='store',
276     dest='with_intl',
277     default='none',
278     choices=valid_intl_modes,
279     help='Intl mode (valid choices: {0}) [default: %default]'.format(
280         ', '.join(valid_intl_modes)))
281
282 intl_optgroup.add_option('--with-icu-path',
283     action='store',
284     dest='with_icu_path',
285     help='Path to icu.gyp (ICU i18n, Chromium version only.)')
286
287 intl_optgroup.add_option('--with-icu-locales',
288     action='store',
289     dest='with_icu_locales',
290     default='root,en',
291     help='Comma-separated list of locales for "small-icu". "root" is assumed. '
292         '[default: %default]')
293
294 intl_optgroup.add_option('--with-icu-source',
295     action='store',
296     dest='with_icu_source',
297     help='Intl mode: optional local path to icu/ dir, or path/URL of icu source archive.')
298
299 intl_optgroup.add_option('--download',
300     action='store',
301     dest='download_list',
302     help=nodedownload.help())
303
304 intl_optgroup.add_option('--download-path',
305     action='store',
306     dest='download_path',
307     default=os.path.join(root_dir, 'deps'),
308     help='Download directory [default: %default]')
309
310 parser.add_option_group(intl_optgroup)
311
312 parser.add_option('--with-perfctr',
313     action='store_true',
314     dest='with_perfctr',
315     help='build with performance counters (default is true on Windows)')
316
317 parser.add_option('--without-dtrace',
318     action='store_true',
319     dest='without_dtrace',
320     help='build without DTrace')
321
322 parser.add_option('--without-etw',
323     action='store_true',
324     dest='without_etw',
325     help='build without ETW')
326
327 parser.add_option('--without-npm',
328     action='store_true',
329     dest='without_npm',
330     help='don\'t install the bundled npm package manager')
331
332 parser.add_option('--without-perfctr',
333     action='store_true',
334     dest='without_perfctr',
335     help='build without performance counters')
336
337 # Dummy option for backwards compatibility
338 parser.add_option('--with-snapshot',
339     action='store_true',
340     dest='unused_with_snapshot',
341     help=optparse.SUPPRESS_HELP)
342
343 parser.add_option('--without-snapshot',
344     action='store_true',
345     dest='without_snapshot',
346     help=optparse.SUPPRESS_HELP)
347
348 parser.add_option('--without-ssl',
349     action='store_true',
350     dest='without_ssl',
351     help='build without SSL')
352
353 parser.add_option('--xcode',
354     action='store_true',
355     dest='use_xcode',
356     help='generate build files for use with xcode')
357
358 parser.add_option('--enable-asan',
359     action='store_true',
360     dest='enable_asan',
361     help='build with asan')
362
363 parser.add_option('--enable-static',
364     action='store_true',
365     dest='enable_static',
366     help='build as static library')
367
368 (options, args) = parser.parse_args()
369
370 # Expand ~ in the install prefix now, it gets written to multiple files.
371 options.prefix = os.path.expanduser(options.prefix or '')
372
373 # set up auto-download list
374 auto_downloads = nodedownload.parse(options.download_list)
375
376
377 def warn(msg):
378   warn.warned = True
379   prefix = '\033[1m\033[93mWARNING\033[0m' if os.isatty(1) else 'WARNING'
380   print('%s: %s' % (prefix, msg))
381
382 # track if warnings occured
383 warn.warned = False
384
385 def b(value):
386   """Returns the string 'true' if value is truthy, 'false' otherwise."""
387   if value:
388     return 'true'
389   else:
390     return 'false'
391
392
393 def pkg_config(pkg):
394   pkg_config = os.environ.get('PKG_CONFIG', 'pkg-config')
395   args = '--silence-errors'
396   retval = ()
397   for flag in ['--libs-only-l', '--cflags-only-I', '--libs-only-L']:
398     try:
399       val = subprocess.check_output([pkg_config, args, flag, pkg])
400       # check_output returns bytes
401       val = val.encode().strip().rstrip('\n')
402     except subprocess.CalledProcessError:
403       # most likely missing a .pc-file
404       val = None
405     except OSError:
406       # no pkg-config/pkgconf installed
407       return (None, None, None)
408     retval += (val,)
409   return retval
410
411
412 def try_check_compiler(cc, lang):
413   try:
414     proc = subprocess.Popen(shlex.split(cc) + ['-E', '-P', '-x', lang, '-'],
415                             stdin=subprocess.PIPE, stdout=subprocess.PIPE)
416   except OSError:
417     return (False, False, '', '')
418
419   proc.stdin.write('__clang__ __GNUC__ __GNUC_MINOR__ __GNUC_PATCHLEVEL__ '
420                    '__clang_major__ __clang_minor__ __clang_patchlevel__')
421
422   values = (proc.communicate()[0].split() + ['0'] * 7)[0:7]
423   is_clang = values[0] == '1'
424   gcc_version = '%s.%s.%s' % tuple(values[1:1+3])
425   clang_version = '%s.%s.%s' % tuple(values[4:4+3])
426
427   return (True, is_clang, clang_version, gcc_version)
428
429
430 #
431 # The version of asm compiler is needed for building openssl asm files.
432 # See deps/openssl/openssl.gypi for detail.
433 # Commands and regular expressions to obtain its version number are taken from
434 # https://github.com/openssl/openssl/blob/OpenSSL_1_0_2-stable/crypto/sha/asm/sha512-x86_64.pl#L112-L129
435 #
436 def get_llvm_version(cc):
437   try:
438     proc = subprocess.Popen(shlex.split(cc) + ['-v'], stdin=subprocess.PIPE,
439                             stderr=subprocess.PIPE, stdout=subprocess.PIPE)
440   except OSError:
441     print '''Node.js configure error: No acceptable C compiler found!
442
443         Please make sure you have a C compiler installed on your system and/or
444         consider adjusting the CC environment variable if you installed
445         it in a non-standard prefix.
446         '''
447     sys.exit()
448
449   match = re.search(r"(^clang version|based on LLVM) ([3-9]\.[0-9]+)",
450                     proc.communicate()[1])
451
452   if match:
453     return match.group(2)
454   else:
455     return 0
456
457
458 def get_gas_version(cc):
459   try:
460     proc = subprocess.Popen(shlex.split(cc) + ['-Wa,-v', '-c', '-o',
461                                                '/dev/null', '-x',
462                                                'assembler',  '/dev/null'],
463                             stdin=subprocess.PIPE, stderr=subprocess.PIPE,
464                             stdout=subprocess.PIPE)
465   except OSError:
466     print '''Node.js configure error: No acceptable C compiler found!
467
468         Please make sure you have a C compiler installed on your system and/or
469         consider adjusting the CC environment variable if you installed
470         it in a non-standard prefix.
471         '''
472     sys.exit()
473
474   match = re.match(r"GNU assembler version ([2-9]\.[0-9]+)",
475                    proc.communicate()[1])
476
477   if match:
478     return match.group(1)
479   else:
480     return 0
481
482 # Note: Apple clang self-reports as clang 4.2.0 and gcc 4.2.1.  It passes
483 # the version check more by accident than anything else but a more rigorous
484 # check involves checking the build number against a whitelist.  I'm not
485 # quite prepared to go that far yet.
486 def check_compiler(o):
487   if sys.platform == 'win32':
488     return
489
490   ok, is_clang, clang_version, gcc_version = try_check_compiler(CXX, 'c++')
491   if not ok:
492     warn('failed to autodetect C++ compiler version (CXX=%s)' % CXX)
493   elif clang_version < '3.4.0' if is_clang else gcc_version < '4.8.0':
494     warn('C++ compiler too old, need g++ 4.8 or clang++ 3.4 (CXX=%s)' % CXX)
495
496   ok, is_clang, clang_version, gcc_version = try_check_compiler(CC, 'c')
497   if not ok:
498     warn('failed to autodetect C compiler version (CC=%s)' % CC)
499   elif not is_clang and gcc_version < '4.2.0':
500     # clang 3.2 is a little white lie because any clang version will probably
501     # do for the C bits.  However, we might as well encourage people to upgrade
502     # to a version that is not completely ancient.
503     warn('C compiler too old, need gcc 4.2 or clang 3.2 (CC=%s)' % CC)
504
505   # Need llvm_version or gas_version when openssl asm files are compiled
506   if options.without_ssl or options.openssl_no_asm or options.shared_openssl:
507     return
508
509   if is_clang:
510     o['variables']['llvm_version'] = get_llvm_version(CC)
511   else:
512     o['variables']['gas_version'] = get_gas_version(CC)
513
514
515 def cc_macros(cc=None):
516   """Checks predefined macros using the C compiler command."""
517
518   try:
519     p = subprocess.Popen(shlex.split(cc or CC) + ['-dM', '-E', '-'],
520                          stdin=subprocess.PIPE,
521                          stdout=subprocess.PIPE,
522                          stderr=subprocess.PIPE)
523   except OSError:
524     print '''Node.js configure error: No acceptable C compiler found!
525
526         Please make sure you have a C compiler installed on your system and/or
527         consider adjusting the CC environment variable if you installed
528         it in a non-standard prefix.
529         '''
530     sys.exit()
531
532   p.stdin.write('\n')
533   out = p.communicate()[0]
534
535   out = str(out).split('\n')
536
537   k = {}
538   for line in out:
539     lst = shlex.split(line)
540     if len(lst) > 2:
541       key = lst[1]
542       val = lst[2]
543       k[key] = val
544   return k
545
546
547 def is_arch_armv7():
548   """Check for ARMv7 instructions"""
549   cc_macros_cache = cc_macros()
550   return cc_macros_cache.get('__ARM_ARCH') == '7'
551
552
553 def is_arch_armv6():
554   """Check for ARMv6 instructions"""
555   cc_macros_cache = cc_macros()
556   return cc_macros_cache.get('__ARM_ARCH') == '6'
557
558
559 def is_arm_hard_float_abi():
560   """Check for hardfloat or softfloat eabi on ARM"""
561   # GCC versions 4.6 and above define __ARM_PCS or __ARM_PCS_VFP to specify
562   # the Floating Point ABI used (PCS stands for Procedure Call Standard).
563   # We use these as well as a couple of other defines to statically determine
564   # what FP ABI used.
565
566   return '__ARM_PCS_VFP' in cc_macros()
567
568
569 def host_arch_cc():
570   """Host architecture check using the CC command."""
571
572   if sys.platform.startswith('aix'):
573     # we only support gcc at this point and the default on AIX
574     # would be xlc so hard code gcc
575     k = cc_macros('gcc')
576   else:
577     k = cc_macros(os.environ.get('CC_host'))
578
579   matchup = {
580     '__aarch64__' : 'arm64',
581     '__arm__'     : 'arm',
582     '__i386__'    : 'ia32',
583     '__MIPSEL__'  : 'mipsel',
584     '__mips__'    : 'mips',
585     '__PPC64__'   : 'ppc64',
586     '__PPC__'     : 'ppc',
587     '__x86_64__'  : 'x64',
588   }
589
590   rtn = 'ia32' # default
591
592   for i in matchup:
593     if i in k and k[i] != '0':
594       rtn = matchup[i]
595       break
596
597   return rtn
598
599
600 def host_arch_win():
601   """Host architecture check using environ vars (better way to do this?)"""
602
603   observed_arch = os.environ.get('PROCESSOR_ARCHITECTURE', 'x86')
604   arch = os.environ.get('PROCESSOR_ARCHITEW6432', observed_arch)
605
606   matchup = {
607     'AMD64'  : 'x64',
608     'x86'    : 'ia32',
609     'arm'    : 'arm',
610     'mips'   : 'mips',
611   }
612
613   return matchup.get(arch, 'ia32')
614
615
616 def configure_arm(o):
617   if options.arm_float_abi:
618     arm_float_abi = options.arm_float_abi
619   elif is_arm_hard_float_abi():
620     arm_float_abi = 'hard'
621   else:
622     arm_float_abi = 'default'
623
624   arm_fpu = 'vfp'
625
626   if is_arch_armv7():
627     arm_fpu = 'vfpv3'
628     o['variables']['arm_version'] = '7'
629   else:
630     o['variables']['arm_version'] = '6' if is_arch_armv6() else 'default'
631
632   o['variables']['arm_thumb'] = 0      # -marm
633   o['variables']['arm_float_abi'] = arm_float_abi
634
635   if options.dest_os == 'android':
636     arm_fpu = 'vfpv3'
637     o['variables']['arm_version'] = '7'
638
639   o['variables']['arm_fpu'] = options.arm_fpu or arm_fpu
640
641
642 def configure_mips(o):
643   can_use_fpu_instructions = (options.mips_float_abi != 'soft')
644   o['variables']['v8_can_use_fpu_instructions'] = b(can_use_fpu_instructions)
645   o['variables']['v8_use_mips_abi_hardfloat'] = b(can_use_fpu_instructions)
646   o['variables']['mips_arch_variant'] = options.mips_arch_variant
647   o['variables']['mips_fpu_mode'] = options.mips_fpu_mode
648
649
650 def configure_node(o):
651   if options.dest_os == 'android':
652     o['variables']['OS'] = 'android'
653   o['variables']['node_prefix'] = options.prefix
654   o['variables']['node_install_npm'] = b(not options.without_npm)
655   o['default_configuration'] = 'Debug' if options.debug else 'Release'
656
657   host_arch = host_arch_win() if os.name == 'nt' else host_arch_cc()
658   target_arch = options.dest_cpu or host_arch
659   # ia32 is preferred by the build tools (GYP) over x86 even if we prefer the latter
660   # the Makefile resets this to x86 afterward
661   if target_arch == 'x86':
662     target_arch = 'ia32'
663   o['variables']['host_arch'] = host_arch
664   o['variables']['target_arch'] = target_arch
665   o['variables']['node_byteorder'] = sys.byteorder
666
667   cross_compiling = target_arch != host_arch
668   want_snapshots = not options.without_snapshot
669   o['variables']['want_separate_host_toolset'] = int(
670       cross_compiling and want_snapshots)
671
672   if target_arch == 'arm':
673     configure_arm(o)
674   elif target_arch in ('mips', 'mipsel'):
675     configure_mips(o)
676
677   if flavor == 'aix':
678     o['variables']['node_core_target_name'] = 'node_base'
679     o['variables']['node_target_type'] = 'static_library'
680
681   if flavor in ('solaris', 'mac', 'linux', 'freebsd'):
682     use_dtrace = not options.without_dtrace
683     # Don't enable by default on linux and freebsd
684     if flavor in ('linux', 'freebsd'):
685       use_dtrace = options.with_dtrace
686
687     if flavor == 'linux':
688       if options.systemtap_includes:
689         o['include_dirs'] += [options.systemtap_includes]
690     o['variables']['node_use_dtrace'] = b(use_dtrace)
691     o['variables']['uv_use_dtrace'] = b(use_dtrace)
692     o['variables']['uv_parent_path'] = '/deps/uv/'
693   elif options.with_dtrace:
694     raise Exception(
695        'DTrace is currently only supported on SunOS, MacOS or Linux systems.')
696   else:
697     o['variables']['node_use_dtrace'] = 'false'
698
699   # Enable Lttng if --with-lttng was defined. Use logic similar to
700   # ETW for windows. Lttng is only available on the Linux platform.
701   if flavor == 'linux':
702     o['variables']['node_use_lttng'] = b(options.with_lttng)
703   elif options.with_lttng:
704     raise Exception('lttng is only supported on Linux.')
705   else:
706     o['variables']['node_use_lttng'] = 'false'
707
708   if options.no_ifaddrs:
709     o['defines'] += ['SUNOS_NO_IFADDRS']
710
711   # By default, enable ETW on Windows.
712   if flavor == 'win':
713     o['variables']['node_use_etw'] = b(not options.without_etw)
714   elif options.with_etw:
715     raise Exception('ETW is only supported on Windows.')
716   else:
717     o['variables']['node_use_etw'] = 'false'
718
719   # By default, enable Performance counters on Windows.
720   if flavor == 'win':
721     o['variables']['node_use_perfctr'] = b(not options.without_perfctr)
722   elif options.with_perfctr:
723     raise Exception('Performance counter is only supported on Windows.')
724   else:
725     o['variables']['node_use_perfctr'] = 'false'
726
727   if options.tag:
728     o['variables']['node_tag'] = '-' + options.tag
729   else:
730     o['variables']['node_tag'] = ''
731
732   o['variables']['node_release_urlbase'] = options.release_urlbase or ''
733
734   if options.v8_options:
735     o['variables']['node_v8_options'] = options.v8_options.replace('"', '\\"')
736
737   if options.enable_static:
738     o['variables']['node_target_type'] = 'static_library'
739
740   if options.linked_module:
741     o['variables']['library_files'] = options.linked_module
742
743   o['variables']['asan'] = int(options.enable_asan or 0)
744
745 def configure_library(lib, output):
746   shared_lib = 'shared_' + lib
747   output['variables']['node_' + shared_lib] = b(getattr(options, shared_lib))
748
749   if getattr(options, shared_lib):
750     (pkg_libs, pkg_cflags, pkg_libpath) = pkg_config(lib)
751
752     if pkg_cflags:
753       output['include_dirs'] += (
754           filter(None, map(str.strip, pkg_cflags.split('-I'))))
755     elif options.__dict__[shared_lib + '_includes']:
756       output['include_dirs'] += [options.__dict__[shared_lib + '_includes']]
757
758     # libpath needs to be provided ahead libraries
759     if pkg_libpath:
760       output['libraries'] += [pkg_libpath]
761     elif options.__dict__[shared_lib + '_libpath']:
762       output['libraries'] += [
763           '-L%s' % options.__dict__[shared_lib + '_libpath']]
764
765     default_libs = getattr(options, shared_lib + '_libname')
766     default_libs = map('-l{0}'.format, default_libs.split(','))
767
768     if pkg_libs:
769       output['libraries'] += pkg_libs.split()
770     elif default_libs:
771       output['libraries'] += default_libs
772
773
774 def configure_v8(o):
775   o['variables']['v8_enable_gdbjit'] = 1 if options.gdb else 0
776   o['variables']['v8_no_strict_aliasing'] = 1  # Work around compiler bugs.
777   o['variables']['v8_optimized_debug'] = 0  # Compile with -O0 in debug builds.
778   o['variables']['v8_random_seed'] = 0  # Use a random seed for hash tables.
779   o['variables']['v8_use_snapshot'] = 'false' if options.without_snapshot else 'true'
780
781 def configure_openssl(o):
782   o['variables']['node_use_openssl'] = b(not options.without_ssl)
783   o['variables']['node_shared_openssl'] = b(options.shared_openssl)
784   o['variables']['openssl_no_asm'] = 1 if options.openssl_no_asm else 0
785   if options.openssl_fips:
786     o['variables']['openssl_fips'] = options.openssl_fips
787     fips_dir = os.path.join(root_dir, 'deps', 'openssl', 'fips')
788     fips_ld = os.path.abspath(os.path.join(fips_dir, 'fipsld'))
789     o['make_fips_settings'] = [
790       ['LINK', fips_ld + ' <(openssl_fips)/bin/fipsld'],
791     ]
792   else:
793     o['variables']['openssl_fips'] = ''
794
795
796   if options.without_ssl:
797     return
798   configure_library('openssl', o)
799
800
801 def configure_static(o):
802   if options.fully_static or options.partly_static:
803     if flavor == 'mac':
804       print("Generation of static executable will not work on OSX "
805             "when using the default compilation environment")
806       return
807
808     if options.fully_static:
809       o['libraries'] += ['-static']
810     elif options.partly_static:
811       o['libraries'] += ['-static-libgcc', '-static-libstdc++']
812       if options.enable_asan:
813         o['libraries'] += ['-static-libasan']
814
815
816 def configure_winsdk(o):
817   if flavor != 'win':
818     return
819
820   winsdk_dir = os.environ.get('WindowsSdkDir')
821
822   if winsdk_dir and os.path.isfile(winsdk_dir + '\\bin\\ctrpp.exe'):
823     print('Found ctrpp in WinSDK--will build generated files '
824           'into tools/msvs/genfiles.')
825     o['variables']['node_has_winsdk'] = 'true'
826     return
827
828   print('ctrpp not found in WinSDK path--using pre-gen files '
829         'from tools/msvs/genfiles.')
830
831 def write(filename, data):
832   filename = os.path.join(root_dir, filename)
833   print 'creating ', filename
834   f = open(filename, 'w+')
835   f.write(data)
836
837 do_not_edit = '# Do not edit. Generated by the configure script.\n'
838
839 def glob_to_var(dir_base, dir_sub, patch_dir):
840   list = []
841   dir_all = os.path.join(dir_base, dir_sub)
842   files = os.walk(dir_all)
843   for ent in files:
844     (path, dirs, files) = ent
845     for file in files:
846       if file.endswith('.cpp') or file.endswith('.c') or file.endswith('.h'):
847         # srcfile uses "slash" as dir separator as its output is consumed by gyp
848         srcfile = '%s/%s' % (dir_sub, file)
849         if patch_dir:
850           patchfile = '%s/%s/%s' % (dir_base, patch_dir, file)
851           if os.path.isfile(patchfile):
852             srcfile = '%s/%s' % (patch_dir, file)
853             print 'Using version-specific floating patch %s' % patchfile
854         list.append(srcfile)
855     break
856   return list
857
858 def configure_intl(o):
859   icus = [
860     {
861       'url': 'https://ssl.icu-project.org/files/icu4c/56.1/icu4c-56_1-src.zip',
862       'md5': '61d71888f14bf00cc3e8a6f2c087d367',
863     },
864   ]
865   def icu_download(path):
866     # download ICU, if needed
867     if not os.access(options.download_path, os.W_OK):
868       print 'Error: cannot write to desired download path. ' \
869             'Either create it or verify permissions.'
870       sys.exit(1)
871     for icu in icus:
872       url = icu['url']
873       md5 = icu['md5']
874       local = url.split('/')[-1]
875       targetfile = os.path.join(options.download_path, local)
876       if not os.path.isfile(targetfile):
877         if nodedownload.candownload(auto_downloads, "icu"):
878           nodedownload.retrievefile(url, targetfile)
879       else:
880         print ' Re-using existing %s' % targetfile
881       if os.path.isfile(targetfile):
882         sys.stdout.write(' Checking file integrity with MD5:\r')
883         gotmd5 = nodedownload.md5sum(targetfile)
884         print ' MD5:      %s  %s' % (gotmd5, targetfile)
885         if (md5 == gotmd5):
886           return targetfile
887         else:
888           print ' Expected: %s      *MISMATCH*' % md5
889           print '\n ** Corrupted ZIP? Delete %s to retry download.\n' % targetfile
890     return None
891   icu_config = {
892     'variables': {}
893   }
894   icu_config_name = 'icu_config.gypi'
895   def write_config(data, name):
896     return
897
898   # write an empty file to start with
899   write(icu_config_name, do_not_edit +
900         pprint.pformat(icu_config, indent=2) + '\n')
901
902   # always set icu_small, node.gyp depends on it being defined.
903   o['variables']['icu_small'] = b(False)
904
905   with_intl = options.with_intl
906   with_icu_source = options.with_icu_source
907   have_icu_path = bool(options.with_icu_path)
908   if have_icu_path and with_intl != 'none':
909     print 'Error: Cannot specify both --with-icu-path and --with-intl'
910     sys.exit(1)
911   elif have_icu_path:
912     # Chromium .gyp mode: --with-icu-path
913     o['variables']['v8_enable_i18n_support'] = 1
914     # use the .gyp given
915     o['variables']['icu_gyp_path'] = options.with_icu_path
916     return
917   # --with-intl=<with_intl>
918   # set the default
919   if with_intl in (None, 'none'):
920     o['variables']['v8_enable_i18n_support'] = 0
921     return  # no Intl
922   elif with_intl == 'small-icu':
923     # small ICU (English only)
924     o['variables']['v8_enable_i18n_support'] = 1
925     o['variables']['icu_small'] = b(True)
926     locs = set(options.with_icu_locales.split(','))
927     locs.add('root')  # must have root
928     o['variables']['icu_locales'] = string.join(locs,',')
929   elif with_intl == 'full-icu':
930     # full ICU
931     o['variables']['v8_enable_i18n_support'] = 1
932   elif with_intl == 'system-icu':
933     # ICU from pkg-config.
934     o['variables']['v8_enable_i18n_support'] = 1
935     pkgicu = pkg_config('icu-i18n')
936     if pkgicu[0] is None:
937       print 'Error: could not load pkg-config data for "icu-i18n".'
938       print 'See above errors or the README.md.'
939       sys.exit(1)
940     (libs, cflags, libpath) = pkgicu
941     # libpath provides linker path which may contain spaces
942     if libpath:
943       o['libraries'] += [libpath]
944     # safe to split, cannot contain spaces
945     o['libraries'] += libs.split()
946     if cflags:
947       o['include_dirs'] += filter(None, map(str.strip, cflags.split('-I')))
948     # use the "system" .gyp
949     o['variables']['icu_gyp_path'] = 'tools/icu/icu-system.gyp'
950     return
951
952   # this is just the 'deps' dir. Used for unpacking.
953   icu_parent_path = os.path.join(root_dir, 'deps')
954
955   # The full path to the ICU source directory.
956   icu_full_path = os.path.join(icu_parent_path, 'icu')
957
958   # icu-tmp is used to download and unpack the ICU tarball.
959   icu_tmp_path = os.path.join(icu_parent_path, 'icu-tmp')
960
961   # --with-icu-source processing
962   # first, check that they didn't pass --with-icu-source=deps/icu
963   if with_icu_source and os.path.abspath(icu_full_path) == os.path.abspath(with_icu_source):
964     print 'Ignoring redundant --with-icu-source=%s' % (with_icu_source)
965     with_icu_source = None
966   # if with_icu_source is still set, try to use it.
967   if with_icu_source:
968     if os.path.isdir(icu_full_path):
969       print 'Deleting old ICU source: %s' % (icu_full_path)
970       shutil.rmtree(icu_full_path)
971     # now, what path was given?
972     if os.path.isdir(with_icu_source):
973       # it's a path. Copy it.
974       print '%s -> %s' % (with_icu_source, icu_full_path)
975       shutil.copytree(with_icu_source, icu_full_path)
976     else:
977       # could be file or URL.
978       # Set up temporary area
979       if os.path.isdir(icu_tmp_path):
980         shutil.rmtree(icu_tmp_path)
981       os.mkdir(icu_tmp_path)
982       icu_tarball = None
983       if os.path.isfile(with_icu_source):
984         # it's a file. Try to unpack it.
985         icu_tarball = with_icu_source
986       else:
987         # Can we download it?
988         local = os.path.join(icu_tmp_path, with_icu_source.split('/')[-1])  # local part
989         icu_tarball = nodedownload.retrievefile(with_icu_source, local)
990       # continue with "icu_tarball"
991       nodedownload.unpack(icu_tarball, icu_tmp_path)
992       # Did it unpack correctly? Should contain 'icu'
993       tmp_icu = os.path.join(icu_tmp_path, 'icu')
994       if os.path.isdir(tmp_icu):
995         os.rename(tmp_icu, icu_full_path)
996         shutil.rmtree(icu_tmp_path)
997       else:
998         print ' Error: --with-icu-source=%s did not result in an "icu" dir.' % with_icu_source
999         shutil.rmtree(icu_tmp_path)
1000         sys.exit(1)
1001
1002   # ICU mode. (icu-generic.gyp)
1003   o['variables']['icu_gyp_path'] = 'tools/icu/icu-generic.gyp'
1004   # ICU source dir relative to root
1005   o['variables']['icu_path'] = icu_full_path
1006   if not os.path.isdir(icu_full_path):
1007     print '* ECMA-402 (Intl) support didn\'t find ICU in %s..' % (icu_full_path)
1008     # can we download (or find) a zipfile?
1009     localzip = icu_download(icu_full_path)
1010     if localzip:
1011       nodedownload.unpack(localzip, icu_parent_path)
1012   if not os.path.isdir(icu_full_path):
1013     print ' Cannot build Intl without ICU in %s.' % (icu_full_path)
1014     print ' (Fix, or disable with "--with-intl=none" )'
1015     sys.exit(1)
1016   else:
1017     print '* Using ICU in %s' % (icu_full_path)
1018   # Now, what version of ICU is it? We just need the "major", such as 54.
1019   # uvernum.h contains it as a #define.
1020   uvernum_h = os.path.join(icu_full_path, 'source/common/unicode/uvernum.h')
1021   if not os.path.isfile(uvernum_h):
1022     print ' Error: could not load %s - is ICU installed?' % uvernum_h
1023     sys.exit(1)
1024   icu_ver_major = None
1025   matchVerExp = r'^\s*#define\s+U_ICU_VERSION_SHORT\s+"([^"]*)".*'
1026   match_version = re.compile(matchVerExp)
1027   for line in open(uvernum_h).readlines():
1028     m = match_version.match(line)
1029     if m:
1030       icu_ver_major = m.group(1)
1031   if not icu_ver_major:
1032     print ' Could not read U_ICU_VERSION_SHORT version from %s' % uvernum_h
1033     sys.exit(1)
1034   icu_endianness = sys.byteorder[0];
1035   o['variables']['icu_ver_major'] = icu_ver_major
1036   o['variables']['icu_endianness'] = icu_endianness
1037   icu_data_file_l = 'icudt%s%s.dat' % (icu_ver_major, 'l')
1038   icu_data_file = 'icudt%s%s.dat' % (icu_ver_major, icu_endianness)
1039   # relative to configure
1040   icu_data_path = os.path.join(icu_full_path,
1041                                'source/data/in',
1042                                icu_data_file_l)
1043   # relative to dep..
1044   icu_data_in = os.path.join('../../deps/icu/source/data/in', icu_data_file_l)
1045   if not os.path.isfile(icu_data_path) and icu_endianness != 'l':
1046     # use host endianness
1047     icu_data_path = os.path.join(icu_full_path,
1048                                  'source/data/in',
1049                                  icu_data_file)
1050     # relative to dep..
1051     icu_data_in = os.path.join('icu/source/data/in',
1052                                icu_data_file)
1053   # this is the input '.dat' file to use .. icudt*.dat
1054   # may be little-endian if from a icu-project.org tarball
1055   o['variables']['icu_data_in'] = icu_data_in
1056   # this is the icudt*.dat file which node will be using (platform endianness)
1057   o['variables']['icu_data_file'] = icu_data_file
1058   if not os.path.isfile(icu_data_path):
1059     print ' Error: ICU prebuilt data file %s does not exist.' % icu_data_path
1060     print ' See the README.md.'
1061     # .. and we're not about to build it from .gyp!
1062     sys.exit(1)
1063   # map from variable name to subdirs
1064   icu_src = {
1065     'stubdata': 'stubdata',
1066     'common': 'common',
1067     'i18n': 'i18n',
1068     'io': 'io',
1069     'tools': 'tools/toolutil',
1070     'genccode': 'tools/genccode',
1071     'genrb': 'tools/genrb',
1072     'icupkg': 'tools/icupkg',
1073   }
1074   # this creates a variable icu_src_XXX for each of the subdirs
1075   # with a list of the src files to use
1076   for i in icu_src:
1077     var  = 'icu_src_%s' % i
1078     path = '../../deps/icu/source/%s' % icu_src[i]
1079     icu_config['variables'][var] = glob_to_var('tools/icu', path, 'patches/%s/source/%s' % (icu_ver_major, icu_src[i]) )
1080   # write updated icu_config.gypi with a bunch of paths
1081   write(icu_config_name, do_not_edit +
1082         pprint.pformat(icu_config, indent=2) + '\n')
1083   return  # end of configure_intl
1084
1085 output = {
1086   'variables': {},
1087   'include_dirs': [],
1088   'libraries': [],
1089   'defines': [],
1090   'cflags': [],
1091 }
1092
1093 # Print a warning when the compiler is too old.
1094 check_compiler(output)
1095
1096 # determine the "flavor" (operating system) we're building for,
1097 # leveraging gyp's GetFlavor function
1098 flavor_params = {}
1099 if (options.dest_os):
1100   flavor_params['flavor'] = options.dest_os
1101 flavor = GetFlavor(flavor_params)
1102
1103 configure_node(output)
1104 configure_library('zlib', output)
1105 configure_library('http_parser', output)
1106 configure_library('libuv', output)
1107 configure_v8(output)
1108 configure_openssl(output)
1109 configure_winsdk(output)
1110 configure_intl(output)
1111 configure_static(output)
1112
1113 # variables should be a root level element,
1114 # move everything else to target_defaults
1115 variables = output['variables']
1116 del output['variables']
1117
1118 # make_global_settings for special FIPS linking
1119 # should not be used to compile modules in node-gyp
1120 config_fips = { 'make_global_settings' : [] }
1121 if 'make_fips_settings' in output:
1122   config_fips['make_global_settings'] = output['make_fips_settings']
1123   del output['make_fips_settings']
1124   write('config_fips.gypi', do_not_edit +
1125         pprint.pformat(config_fips, indent=2) + '\n')
1126
1127 # make_global_settings should be a root level element too
1128 if 'make_global_settings' in output:
1129   make_global_settings = output['make_global_settings']
1130   del output['make_global_settings']
1131 else:
1132   make_global_settings = False
1133
1134 output = {
1135   'variables': variables,
1136   'target_defaults': output,
1137 }
1138 if make_global_settings:
1139   output['make_global_settings'] = make_global_settings
1140
1141 pprint.pprint(output, indent=2)
1142
1143 write('config.gypi', do_not_edit +
1144       pprint.pformat(output, indent=2) + '\n')
1145
1146 config = {
1147   'BUILDTYPE': 'Debug' if options.debug else 'Release',
1148   'USE_XCODE': str(int(options.use_xcode or 0)),
1149   'PYTHON': sys.executable,
1150 }
1151
1152 if options.prefix:
1153   config['PREFIX'] = options.prefix
1154
1155 config = '\n'.join(map('='.join, config.iteritems())) + '\n'
1156
1157 write('config.mk',
1158       '# Do not edit. Generated by the configure script.\n' + config)
1159
1160 gyp_args = [sys.executable, 'tools/gyp_node.py', '--no-parallel']
1161
1162 if options.use_xcode:
1163   gyp_args += ['-f', 'xcode']
1164 elif flavor == 'win' and sys.platform != 'msys':
1165   gyp_args += ['-f', 'msvs', '-G', 'msvs_version=auto']
1166 else:
1167   gyp_args += ['-f', 'make-' + flavor]
1168
1169 gyp_args += args
1170
1171 if warn.warned:
1172   warn('warnings were emitted in the configure phase')
1173
1174 sys.exit(subprocess.call(gyp_args))