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