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