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