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