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