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