test: add test-npm-install to parallel tests suite
[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_version_helper(cc, regexp):
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(regexp, proc.communicate()[1])
450
451   if match:
452     return match.group(2)
453   else:
454     return 0
455
456 def get_llvm_version(cc):
457   return get_version_helper(
458       cc, r"(^clang version|based on LLVM) ([3-9]\.[0-9]+)")
459
460 def get_xcode_version(cc):
461   return get_version_helper(
462       cc, r"(^Apple LLVM version) ([5-9]\.[0-9]+)")
463
464 def get_gas_version(cc):
465   try:
466     proc = subprocess.Popen(shlex.split(cc) + ['-Wa,-v', '-c', '-o',
467                                                '/dev/null', '-x',
468                                                'assembler',  '/dev/null'],
469                             stdin=subprocess.PIPE, stderr=subprocess.PIPE,
470                             stdout=subprocess.PIPE)
471   except OSError:
472     print '''Node.js configure error: No acceptable C compiler found!
473
474         Please make sure you have a C compiler installed on your system and/or
475         consider adjusting the CC environment variable if you installed
476         it in a non-standard prefix.
477         '''
478     sys.exit()
479
480   match = re.match(r"GNU assembler version ([2-9]\.[0-9]+)",
481                    proc.communicate()[1])
482
483   if match:
484     return match.group(1)
485   else:
486     return 0
487
488 # Note: Apple clang self-reports as clang 4.2.0 and gcc 4.2.1.  It passes
489 # the version check more by accident than anything else but a more rigorous
490 # check involves checking the build number against a whitelist.  I'm not
491 # quite prepared to go that far yet.
492 def check_compiler(o):
493   if sys.platform == 'win32':
494     return
495
496   ok, is_clang, clang_version, gcc_version = try_check_compiler(CXX, 'c++')
497   if not ok:
498     warn('failed to autodetect C++ compiler version (CXX=%s)' % CXX)
499   elif clang_version < '3.4.0' if is_clang else gcc_version < '4.8.0':
500     warn('C++ compiler too old, need g++ 4.8 or clang++ 3.4 (CXX=%s)' % CXX)
501
502   ok, is_clang, clang_version, gcc_version = try_check_compiler(CC, 'c')
503   if not ok:
504     warn('failed to autodetect C compiler version (CC=%s)' % CC)
505   elif not is_clang and gcc_version < '4.2.0':
506     # clang 3.2 is a little white lie because any clang version will probably
507     # do for the C bits.  However, we might as well encourage people to upgrade
508     # to a version that is not completely ancient.
509     warn('C compiler too old, need gcc 4.2 or clang 3.2 (CC=%s)' % CC)
510
511   # Need llvm_version or gas_version when openssl asm files are compiled
512   if options.without_ssl or options.openssl_no_asm or options.shared_openssl:
513     return
514
515   if is_clang:
516     o['variables']['llvm_version'] = get_llvm_version(CC)
517     if sys.platform == 'darwin':
518       o['variables']['xcode_version'] = get_xcode_version(CC)
519   else:
520     o['variables']['gas_version'] = get_gas_version(CC)
521
522
523 def cc_macros(cc=None):
524   """Checks predefined macros using the C compiler command."""
525
526   try:
527     p = subprocess.Popen(shlex.split(cc or CC) + ['-dM', '-E', '-'],
528                          stdin=subprocess.PIPE,
529                          stdout=subprocess.PIPE,
530                          stderr=subprocess.PIPE)
531   except OSError:
532     print '''Node.js configure error: No acceptable C compiler found!
533
534         Please make sure you have a C compiler installed on your system and/or
535         consider adjusting the CC environment variable if you installed
536         it in a non-standard prefix.
537         '''
538     sys.exit()
539
540   p.stdin.write('\n')
541   out = p.communicate()[0]
542
543   out = str(out).split('\n')
544
545   k = {}
546   for line in out:
547     lst = shlex.split(line)
548     if len(lst) > 2:
549       key = lst[1]
550       val = lst[2]
551       k[key] = val
552   return k
553
554
555 def is_arch_armv7():
556   """Check for ARMv7 instructions"""
557   cc_macros_cache = cc_macros()
558   return cc_macros_cache.get('__ARM_ARCH') == '7'
559
560
561 def is_arch_armv6():
562   """Check for ARMv6 instructions"""
563   cc_macros_cache = cc_macros()
564   return cc_macros_cache.get('__ARM_ARCH') == '6'
565
566
567 def is_arm_hard_float_abi():
568   """Check for hardfloat or softfloat eabi on ARM"""
569   # GCC versions 4.6 and above define __ARM_PCS or __ARM_PCS_VFP to specify
570   # the Floating Point ABI used (PCS stands for Procedure Call Standard).
571   # We use these as well as a couple of other defines to statically determine
572   # what FP ABI used.
573
574   return '__ARM_PCS_VFP' in cc_macros()
575
576
577 def host_arch_cc():
578   """Host architecture check using the CC command."""
579
580   if sys.platform.startswith('aix'):
581     # we only support gcc at this point and the default on AIX
582     # would be xlc so hard code gcc
583     k = cc_macros('gcc')
584   else:
585     k = cc_macros(os.environ.get('CC_host'))
586
587   matchup = {
588     '__aarch64__' : 'arm64',
589     '__arm__'     : 'arm',
590     '__i386__'    : 'ia32',
591     '__MIPSEL__'  : 'mipsel',
592     '__mips__'    : 'mips',
593     '__PPC64__'   : 'ppc64',
594     '__PPC__'     : 'ppc',
595     '__x86_64__'  : 'x64',
596   }
597
598   rtn = 'ia32' # default
599
600   for i in matchup:
601     if i in k and k[i] != '0':
602       rtn = matchup[i]
603       break
604
605   return rtn
606
607
608 def host_arch_win():
609   """Host architecture check using environ vars (better way to do this?)"""
610
611   observed_arch = os.environ.get('PROCESSOR_ARCHITECTURE', 'x86')
612   arch = os.environ.get('PROCESSOR_ARCHITEW6432', observed_arch)
613
614   matchup = {
615     'AMD64'  : 'x64',
616     'x86'    : 'ia32',
617     'arm'    : 'arm',
618     'mips'   : 'mips',
619   }
620
621   return matchup.get(arch, 'ia32')
622
623
624 def configure_arm(o):
625   if options.arm_float_abi:
626     arm_float_abi = options.arm_float_abi
627   elif is_arm_hard_float_abi():
628     arm_float_abi = 'hard'
629   else:
630     arm_float_abi = 'default'
631
632   arm_fpu = 'vfp'
633
634   if is_arch_armv7():
635     arm_fpu = 'vfpv3'
636     o['variables']['arm_version'] = '7'
637   else:
638     o['variables']['arm_version'] = '6' if is_arch_armv6() else 'default'
639
640   o['variables']['arm_thumb'] = 0      # -marm
641   o['variables']['arm_float_abi'] = arm_float_abi
642
643   if options.dest_os == 'android':
644     arm_fpu = 'vfpv3'
645     o['variables']['arm_version'] = '7'
646
647   o['variables']['arm_fpu'] = options.arm_fpu or arm_fpu
648
649
650 def configure_mips(o):
651   can_use_fpu_instructions = (options.mips_float_abi != 'soft')
652   o['variables']['v8_can_use_fpu_instructions'] = b(can_use_fpu_instructions)
653   o['variables']['v8_use_mips_abi_hardfloat'] = b(can_use_fpu_instructions)
654   o['variables']['mips_arch_variant'] = options.mips_arch_variant
655   o['variables']['mips_fpu_mode'] = options.mips_fpu_mode
656
657
658 def configure_node(o):
659   if options.dest_os == 'android':
660     o['variables']['OS'] = 'android'
661   o['variables']['node_prefix'] = options.prefix
662   o['variables']['node_install_npm'] = b(not options.without_npm)
663   o['default_configuration'] = 'Debug' if options.debug else 'Release'
664
665   host_arch = host_arch_win() if os.name == 'nt' else host_arch_cc()
666   target_arch = options.dest_cpu or host_arch
667   # ia32 is preferred by the build tools (GYP) over x86 even if we prefer the latter
668   # the Makefile resets this to x86 afterward
669   if target_arch == 'x86':
670     target_arch = 'ia32'
671   o['variables']['host_arch'] = host_arch
672   o['variables']['target_arch'] = target_arch
673   o['variables']['node_byteorder'] = sys.byteorder
674
675   cross_compiling = target_arch != host_arch
676   want_snapshots = not options.without_snapshot
677   o['variables']['want_separate_host_toolset'] = int(
678       cross_compiling and want_snapshots)
679
680   if target_arch == 'arm':
681     configure_arm(o)
682   elif target_arch in ('mips', 'mipsel'):
683     configure_mips(o)
684
685   if flavor == 'aix':
686     o['variables']['node_core_target_name'] = 'node_base'
687     o['variables']['node_target_type'] = 'static_library'
688
689   if flavor in ('solaris', 'mac', 'linux', 'freebsd'):
690     use_dtrace = not options.without_dtrace
691     # Don't enable by default on linux and freebsd
692     if flavor in ('linux', 'freebsd'):
693       use_dtrace = options.with_dtrace
694
695     if flavor == 'linux':
696       if options.systemtap_includes:
697         o['include_dirs'] += [options.systemtap_includes]
698     o['variables']['node_use_dtrace'] = b(use_dtrace)
699     o['variables']['uv_use_dtrace'] = b(use_dtrace)
700     o['variables']['uv_parent_path'] = '/deps/uv/'
701   elif options.with_dtrace:
702     raise Exception(
703        'DTrace is currently only supported on SunOS, MacOS or Linux systems.')
704   else:
705     o['variables']['node_use_dtrace'] = 'false'
706
707   # Enable Lttng if --with-lttng was defined. Use logic similar to
708   # ETW for windows. Lttng is only available on the Linux platform.
709   if flavor == 'linux':
710     o['variables']['node_use_lttng'] = b(options.with_lttng)
711   elif options.with_lttng:
712     raise Exception('lttng is only supported on Linux.')
713   else:
714     o['variables']['node_use_lttng'] = 'false'
715
716   if options.no_ifaddrs:
717     o['defines'] += ['SUNOS_NO_IFADDRS']
718
719   # By default, enable ETW on Windows.
720   if flavor == 'win':
721     o['variables']['node_use_etw'] = b(not options.without_etw)
722   elif options.with_etw:
723     raise Exception('ETW is only supported on Windows.')
724   else:
725     o['variables']['node_use_etw'] = 'false'
726
727   # By default, enable Performance counters on Windows.
728   if flavor == 'win':
729     o['variables']['node_use_perfctr'] = b(not options.without_perfctr)
730   elif options.with_perfctr:
731     raise Exception('Performance counter is only supported on Windows.')
732   else:
733     o['variables']['node_use_perfctr'] = 'false'
734
735   if options.tag:
736     o['variables']['node_tag'] = '-' + options.tag
737   else:
738     o['variables']['node_tag'] = ''
739
740   o['variables']['node_release_urlbase'] = options.release_urlbase or ''
741
742   if options.v8_options:
743     o['variables']['node_v8_options'] = options.v8_options.replace('"', '\\"')
744
745   if options.enable_static:
746     o['variables']['node_target_type'] = 'static_library'
747
748   if options.linked_module:
749     o['variables']['library_files'] = options.linked_module
750
751   o['variables']['asan'] = int(options.enable_asan or 0)
752
753 def configure_library(lib, output):
754   shared_lib = 'shared_' + lib
755   output['variables']['node_' + shared_lib] = b(getattr(options, shared_lib))
756
757   if getattr(options, shared_lib):
758     (pkg_libs, pkg_cflags, pkg_libpath) = pkg_config(lib)
759
760     if pkg_cflags:
761       output['include_dirs'] += (
762           filter(None, map(str.strip, pkg_cflags.split('-I'))))
763     elif options.__dict__[shared_lib + '_includes']:
764       output['include_dirs'] += [options.__dict__[shared_lib + '_includes']]
765
766     # libpath needs to be provided ahead libraries
767     if pkg_libpath:
768       output['libraries'] += [pkg_libpath]
769     elif options.__dict__[shared_lib + '_libpath']:
770       output['libraries'] += [
771           '-L%s' % options.__dict__[shared_lib + '_libpath']]
772
773     default_libs = getattr(options, shared_lib + '_libname')
774     default_libs = map('-l{0}'.format, default_libs.split(','))
775
776     if pkg_libs:
777       output['libraries'] += pkg_libs.split()
778     elif default_libs:
779       output['libraries'] += default_libs
780
781
782 def configure_v8(o):
783   o['variables']['v8_enable_gdbjit'] = 1 if options.gdb else 0
784   o['variables']['v8_no_strict_aliasing'] = 1  # Work around compiler bugs.
785   o['variables']['v8_optimized_debug'] = 0  # Compile with -O0 in debug builds.
786   o['variables']['v8_random_seed'] = 0  # Use a random seed for hash tables.
787   o['variables']['v8_use_snapshot'] = 'false' if options.without_snapshot else 'true'
788
789 def configure_openssl(o):
790   o['variables']['node_use_openssl'] = b(not options.without_ssl)
791   o['variables']['node_shared_openssl'] = b(options.shared_openssl)
792   o['variables']['openssl_no_asm'] = 1 if options.openssl_no_asm else 0
793   if options.openssl_fips:
794     o['variables']['openssl_fips'] = options.openssl_fips
795     fips_dir = os.path.join(root_dir, 'deps', 'openssl', 'fips')
796     fips_ld = os.path.abspath(os.path.join(fips_dir, 'fipsld'))
797     o['make_fips_settings'] = [
798       ['LINK', fips_ld + ' <(openssl_fips)/bin/fipsld'],
799     ]
800   else:
801     o['variables']['openssl_fips'] = ''
802
803
804   if options.without_ssl:
805     return
806   configure_library('openssl', o)
807
808
809 def configure_static(o):
810   if options.fully_static or options.partly_static:
811     if flavor == 'mac':
812       print("Generation of static executable will not work on OSX "
813             "when using the default compilation environment")
814       return
815
816     if options.fully_static:
817       o['libraries'] += ['-static']
818     elif options.partly_static:
819       o['libraries'] += ['-static-libgcc', '-static-libstdc++']
820       if options.enable_asan:
821         o['libraries'] += ['-static-libasan']
822
823
824 def configure_winsdk(o):
825   if flavor != 'win':
826     return
827
828   winsdk_dir = os.environ.get('WindowsSdkDir')
829
830   if winsdk_dir and os.path.isfile(winsdk_dir + '\\bin\\ctrpp.exe'):
831     print('Found ctrpp in WinSDK--will build generated files '
832           'into tools/msvs/genfiles.')
833     o['variables']['node_has_winsdk'] = 'true'
834     return
835
836   print('ctrpp not found in WinSDK path--using pre-gen files '
837         'from tools/msvs/genfiles.')
838
839 def write(filename, data):
840   filename = os.path.join(root_dir, filename)
841   print 'creating ', filename
842   f = open(filename, 'w+')
843   f.write(data)
844
845 do_not_edit = '# Do not edit. Generated by the configure script.\n'
846
847 def glob_to_var(dir_base, dir_sub, patch_dir):
848   list = []
849   dir_all = os.path.join(dir_base, dir_sub)
850   files = os.walk(dir_all)
851   for ent in files:
852     (path, dirs, files) = ent
853     for file in files:
854       if file.endswith('.cpp') or file.endswith('.c') or file.endswith('.h'):
855         # srcfile uses "slash" as dir separator as its output is consumed by gyp
856         srcfile = '%s/%s' % (dir_sub, file)
857         if patch_dir:
858           patchfile = '%s/%s/%s' % (dir_base, patch_dir, file)
859           if os.path.isfile(patchfile):
860             srcfile = '%s/%s' % (patch_dir, file)
861             print 'Using version-specific floating patch %s' % patchfile
862         list.append(srcfile)
863     break
864   return list
865
866 def configure_intl(o):
867   icus = [
868     {
869       'url': 'https://ssl.icu-project.org/files/icu4c/56.1/icu4c-56_1-src.zip',
870       'md5': '61d71888f14bf00cc3e8a6f2c087d367',
871     },
872   ]
873   def icu_download(path):
874     # download ICU, if needed
875     if not os.access(options.download_path, os.W_OK):
876       print 'Error: cannot write to desired download path. ' \
877             'Either create it or verify permissions.'
878       sys.exit(1)
879     for icu in icus:
880       url = icu['url']
881       md5 = icu['md5']
882       local = url.split('/')[-1]
883       targetfile = os.path.join(options.download_path, local)
884       if not os.path.isfile(targetfile):
885         if nodedownload.candownload(auto_downloads, "icu"):
886           nodedownload.retrievefile(url, targetfile)
887       else:
888         print ' Re-using existing %s' % targetfile
889       if os.path.isfile(targetfile):
890         sys.stdout.write(' Checking file integrity with MD5:\r')
891         gotmd5 = nodedownload.md5sum(targetfile)
892         print ' MD5:      %s  %s' % (gotmd5, targetfile)
893         if (md5 == gotmd5):
894           return targetfile
895         else:
896           print ' Expected: %s      *MISMATCH*' % md5
897           print '\n ** Corrupted ZIP? Delete %s to retry download.\n' % targetfile
898     return None
899   icu_config = {
900     'variables': {}
901   }
902   icu_config_name = 'icu_config.gypi'
903   def write_config(data, name):
904     return
905
906   # write an empty file to start with
907   write(icu_config_name, do_not_edit +
908         pprint.pformat(icu_config, indent=2) + '\n')
909
910   # always set icu_small, node.gyp depends on it being defined.
911   o['variables']['icu_small'] = b(False)
912
913   with_intl = options.with_intl
914   with_icu_source = options.with_icu_source
915   have_icu_path = bool(options.with_icu_path)
916   if have_icu_path and with_intl != 'none':
917     print 'Error: Cannot specify both --with-icu-path and --with-intl'
918     sys.exit(1)
919   elif have_icu_path:
920     # Chromium .gyp mode: --with-icu-path
921     o['variables']['v8_enable_i18n_support'] = 1
922     # use the .gyp given
923     o['variables']['icu_gyp_path'] = options.with_icu_path
924     return
925   # --with-intl=<with_intl>
926   # set the default
927   if with_intl in (None, 'none'):
928     o['variables']['v8_enable_i18n_support'] = 0
929     return  # no Intl
930   elif with_intl == 'small-icu':
931     # small ICU (English only)
932     o['variables']['v8_enable_i18n_support'] = 1
933     o['variables']['icu_small'] = b(True)
934     locs = set(options.with_icu_locales.split(','))
935     locs.add('root')  # must have root
936     o['variables']['icu_locales'] = string.join(locs,',')
937   elif with_intl == 'full-icu':
938     # full ICU
939     o['variables']['v8_enable_i18n_support'] = 1
940   elif with_intl == 'system-icu':
941     # ICU from pkg-config.
942     o['variables']['v8_enable_i18n_support'] = 1
943     pkgicu = pkg_config('icu-i18n')
944     if pkgicu[0] is None:
945       print 'Error: could not load pkg-config data for "icu-i18n".'
946       print 'See above errors or the README.md.'
947       sys.exit(1)
948     (libs, cflags, libpath) = pkgicu
949     # libpath provides linker path which may contain spaces
950     if libpath:
951       o['libraries'] += [libpath]
952     # safe to split, cannot contain spaces
953     o['libraries'] += libs.split()
954     if cflags:
955       o['include_dirs'] += filter(None, map(str.strip, cflags.split('-I')))
956     # use the "system" .gyp
957     o['variables']['icu_gyp_path'] = 'tools/icu/icu-system.gyp'
958     return
959
960   # this is just the 'deps' dir. Used for unpacking.
961   icu_parent_path = os.path.join(root_dir, 'deps')
962
963   # The full path to the ICU source directory.
964   icu_full_path = os.path.join(icu_parent_path, 'icu')
965
966   # icu-tmp is used to download and unpack the ICU tarball.
967   icu_tmp_path = os.path.join(icu_parent_path, 'icu-tmp')
968
969   # --with-icu-source processing
970   # first, check that they didn't pass --with-icu-source=deps/icu
971   if with_icu_source and os.path.abspath(icu_full_path) == os.path.abspath(with_icu_source):
972     print 'Ignoring redundant --with-icu-source=%s' % (with_icu_source)
973     with_icu_source = None
974   # if with_icu_source is still set, try to use it.
975   if with_icu_source:
976     if os.path.isdir(icu_full_path):
977       print 'Deleting old ICU source: %s' % (icu_full_path)
978       shutil.rmtree(icu_full_path)
979     # now, what path was given?
980     if os.path.isdir(with_icu_source):
981       # it's a path. Copy it.
982       print '%s -> %s' % (with_icu_source, icu_full_path)
983       shutil.copytree(with_icu_source, icu_full_path)
984     else:
985       # could be file or URL.
986       # Set up temporary area
987       if os.path.isdir(icu_tmp_path):
988         shutil.rmtree(icu_tmp_path)
989       os.mkdir(icu_tmp_path)
990       icu_tarball = None
991       if os.path.isfile(with_icu_source):
992         # it's a file. Try to unpack it.
993         icu_tarball = with_icu_source
994       else:
995         # Can we download it?
996         local = os.path.join(icu_tmp_path, with_icu_source.split('/')[-1])  # local part
997         icu_tarball = nodedownload.retrievefile(with_icu_source, local)
998       # continue with "icu_tarball"
999       nodedownload.unpack(icu_tarball, icu_tmp_path)
1000       # Did it unpack correctly? Should contain 'icu'
1001       tmp_icu = os.path.join(icu_tmp_path, 'icu')
1002       if os.path.isdir(tmp_icu):
1003         os.rename(tmp_icu, icu_full_path)
1004         shutil.rmtree(icu_tmp_path)
1005       else:
1006         print ' Error: --with-icu-source=%s did not result in an "icu" dir.' % with_icu_source
1007         shutil.rmtree(icu_tmp_path)
1008         sys.exit(1)
1009
1010   # ICU mode. (icu-generic.gyp)
1011   o['variables']['icu_gyp_path'] = 'tools/icu/icu-generic.gyp'
1012   # ICU source dir relative to root
1013   o['variables']['icu_path'] = icu_full_path
1014   if not os.path.isdir(icu_full_path):
1015     print '* ECMA-402 (Intl) support didn\'t find ICU in %s..' % (icu_full_path)
1016     # can we download (or find) a zipfile?
1017     localzip = icu_download(icu_full_path)
1018     if localzip:
1019       nodedownload.unpack(localzip, icu_parent_path)
1020   if not os.path.isdir(icu_full_path):
1021     print ' Cannot build Intl without ICU in %s.' % (icu_full_path)
1022     print ' (Fix, or disable with "--with-intl=none" )'
1023     sys.exit(1)
1024   else:
1025     print '* Using ICU in %s' % (icu_full_path)
1026   # Now, what version of ICU is it? We just need the "major", such as 54.
1027   # uvernum.h contains it as a #define.
1028   uvernum_h = os.path.join(icu_full_path, 'source/common/unicode/uvernum.h')
1029   if not os.path.isfile(uvernum_h):
1030     print ' Error: could not load %s - is ICU installed?' % uvernum_h
1031     sys.exit(1)
1032   icu_ver_major = None
1033   matchVerExp = r'^\s*#define\s+U_ICU_VERSION_SHORT\s+"([^"]*)".*'
1034   match_version = re.compile(matchVerExp)
1035   for line in open(uvernum_h).readlines():
1036     m = match_version.match(line)
1037     if m:
1038       icu_ver_major = m.group(1)
1039   if not icu_ver_major:
1040     print ' Could not read U_ICU_VERSION_SHORT version from %s' % uvernum_h
1041     sys.exit(1)
1042   icu_endianness = sys.byteorder[0];
1043   o['variables']['icu_ver_major'] = icu_ver_major
1044   o['variables']['icu_endianness'] = icu_endianness
1045   icu_data_file_l = 'icudt%s%s.dat' % (icu_ver_major, 'l')
1046   icu_data_file = 'icudt%s%s.dat' % (icu_ver_major, icu_endianness)
1047   # relative to configure
1048   icu_data_path = os.path.join(icu_full_path,
1049                                'source/data/in',
1050                                icu_data_file_l)
1051   # relative to dep..
1052   icu_data_in = os.path.join('../../deps/icu/source/data/in', icu_data_file_l)
1053   if not os.path.isfile(icu_data_path) and icu_endianness != 'l':
1054     # use host endianness
1055     icu_data_path = os.path.join(icu_full_path,
1056                                  'source/data/in',
1057                                  icu_data_file)
1058     # relative to dep..
1059     icu_data_in = os.path.join('icu/source/data/in',
1060                                icu_data_file)
1061   # this is the input '.dat' file to use .. icudt*.dat
1062   # may be little-endian if from a icu-project.org tarball
1063   o['variables']['icu_data_in'] = icu_data_in
1064   # this is the icudt*.dat file which node will be using (platform endianness)
1065   o['variables']['icu_data_file'] = icu_data_file
1066   if not os.path.isfile(icu_data_path):
1067     print ' Error: ICU prebuilt data file %s does not exist.' % icu_data_path
1068     print ' See the README.md.'
1069     # .. and we're not about to build it from .gyp!
1070     sys.exit(1)
1071   # map from variable name to subdirs
1072   icu_src = {
1073     'stubdata': 'stubdata',
1074     'common': 'common',
1075     'i18n': 'i18n',
1076     'io': 'io',
1077     'tools': 'tools/toolutil',
1078     'genccode': 'tools/genccode',
1079     'genrb': 'tools/genrb',
1080     'icupkg': 'tools/icupkg',
1081   }
1082   # this creates a variable icu_src_XXX for each of the subdirs
1083   # with a list of the src files to use
1084   for i in icu_src:
1085     var  = 'icu_src_%s' % i
1086     path = '../../deps/icu/source/%s' % icu_src[i]
1087     icu_config['variables'][var] = glob_to_var('tools/icu', path, 'patches/%s/source/%s' % (icu_ver_major, icu_src[i]) )
1088   # write updated icu_config.gypi with a bunch of paths
1089   write(icu_config_name, do_not_edit +
1090         pprint.pformat(icu_config, indent=2) + '\n')
1091   return  # end of configure_intl
1092
1093 output = {
1094   'variables': {},
1095   'include_dirs': [],
1096   'libraries': [],
1097   'defines': [],
1098   'cflags': [],
1099 }
1100
1101 # Print a warning when the compiler is too old.
1102 check_compiler(output)
1103
1104 # determine the "flavor" (operating system) we're building for,
1105 # leveraging gyp's GetFlavor function
1106 flavor_params = {}
1107 if (options.dest_os):
1108   flavor_params['flavor'] = options.dest_os
1109 flavor = GetFlavor(flavor_params)
1110
1111 configure_node(output)
1112 configure_library('zlib', output)
1113 configure_library('http_parser', output)
1114 configure_library('libuv', output)
1115 configure_v8(output)
1116 configure_openssl(output)
1117 configure_winsdk(output)
1118 configure_intl(output)
1119 configure_static(output)
1120
1121 # variables should be a root level element,
1122 # move everything else to target_defaults
1123 variables = output['variables']
1124 del output['variables']
1125
1126 # make_global_settings for special FIPS linking
1127 # should not be used to compile modules in node-gyp
1128 config_fips = { 'make_global_settings' : [] }
1129 if 'make_fips_settings' in output:
1130   config_fips['make_global_settings'] = output['make_fips_settings']
1131   del output['make_fips_settings']
1132   write('config_fips.gypi', do_not_edit +
1133         pprint.pformat(config_fips, indent=2) + '\n')
1134
1135 # make_global_settings should be a root level element too
1136 if 'make_global_settings' in output:
1137   make_global_settings = output['make_global_settings']
1138   del output['make_global_settings']
1139 else:
1140   make_global_settings = False
1141
1142 output = {
1143   'variables': variables,
1144   'target_defaults': output,
1145 }
1146 if make_global_settings:
1147   output['make_global_settings'] = make_global_settings
1148
1149 pprint.pprint(output, indent=2)
1150
1151 write('config.gypi', do_not_edit +
1152       pprint.pformat(output, indent=2) + '\n')
1153
1154 config = {
1155   'BUILDTYPE': 'Debug' if options.debug else 'Release',
1156   'USE_XCODE': str(int(options.use_xcode or 0)),
1157   'PYTHON': sys.executable,
1158 }
1159
1160 if options.prefix:
1161   config['PREFIX'] = options.prefix
1162
1163 config = '\n'.join(map('='.join, config.iteritems())) + '\n'
1164
1165 write('config.mk',
1166       '# Do not edit. Generated by the configure script.\n' + config)
1167
1168 gyp_args = [sys.executable, 'tools/gyp_node.py', '--no-parallel']
1169
1170 if options.use_xcode:
1171   gyp_args += ['-f', 'xcode']
1172 elif flavor == 'win' and sys.platform != 'msys':
1173   gyp_args += ['-f', 'msvs', '-G', 'msvs_version=auto']
1174 else:
1175   gyp_args += ['-f', 'make-' + flavor]
1176
1177 gyp_args += args
1178
1179 if warn.warned:
1180   warn('warnings were emitted in the configure phase')
1181
1182 sys.exit(subprocess.call(gyp_args))