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