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