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