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