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