Following the license change, modify the boilerplates in crypto/comp/
[openssl.git] / Configure
1 #! /usr/bin/env perl
2 # -*- mode: perl; -*-
3 # Copyright 2016-2018 The OpenSSL Project Authors. All Rights Reserved.
4 #
5 # Licensed under the OpenSSL license (the "License").  You may not use
6 # this file except in compliance with the License.  You can obtain a copy
7 # in the file LICENSE in the source distribution or at
8 # https://www.openssl.org/source/license.html
9
10 ##  Configure -- OpenSSL source tree configuration script
11
12 use 5.10.0;
13 use strict;
14 use Config;
15 use FindBin;
16 use lib "$FindBin::Bin/util/perl";
17 use File::Basename;
18 use File::Spec::Functions qw/:DEFAULT abs2rel rel2abs splitdir/;
19 use File::Path qw/mkpath/;
20 use OpenSSL::Glob;
21
22 # see INSTALL for instructions.
23
24 my $orig_death_handler = $SIG{__DIE__};
25 $SIG{__DIE__} = \&death_handler;
26
27 my $usage="Usage: Configure [no-<cipher> ...] [enable-<cipher> ...] [-Dxxx] [-lxxx] [-Lxxx] [-fxxx] [-Kxxx] [no-hw-xxx|no-hw] [[no-]threads] [[no-]shared] [[no-]zlib|zlib-dynamic] [no-asm] [no-dso] [no-egd] [sctp] [386] [--prefix=DIR] [--openssldir=OPENSSLDIR] [--with-xxx[=vvv]] [--config=FILE] os/compiler[:flags]\n";
28
29 # Options:
30 #
31 # --config      add the given configuration file, which will be read after
32 #               any "Configurations*" files that are found in the same
33 #               directory as this script.
34 # --prefix      prefix for the OpenSSL installation, which includes the
35 #               directories bin, lib, include, share/man, share/doc/openssl
36 #               This becomes the value of INSTALLTOP in Makefile
37 #               (Default: /usr/local)
38 # --openssldir  OpenSSL data area, such as openssl.cnf, certificates and keys.
39 #               If it's a relative directory, it will be added on the directory
40 #               given with --prefix.
41 #               This becomes the value of OPENSSLDIR in Makefile and in C.
42 #               (Default: PREFIX/ssl)
43 #
44 # --cross-compile-prefix Add specified prefix to binutils components.
45 #
46 # --api         One of 0.9.8, 1.0.0, 1.0.1, 1.0.2, 1.1.0, 1.1.1, or 3.0.0 / 3.
47 #               Do not compile support for interfaces deprecated as of the
48 #               specified OpenSSL version.
49 #
50 # no-hw-xxx     do not compile support for specific crypto hardware.
51 #               Generic OpenSSL-style methods relating to this support
52 #               are always compiled but return NULL if the hardware
53 #               support isn't compiled.
54 # no-hw         do not compile support for any crypto hardware.
55 # [no-]threads  [don't] try to create a library that is suitable for
56 #               multithreaded applications (default is "threads" if we
57 #               know how to do it)
58 # [no-]shared   [don't] try to create shared libraries when supported.
59 # [no-]pic      [don't] try to build position independent code when supported.
60 #               If disabled, it also disables shared and dynamic-engine.
61 # no-asm        do not use assembler
62 # no-dso        do not compile in any native shared-library methods. This
63 #               will ensure that all methods just return NULL.
64 # no-egd        do not compile support for the entropy-gathering daemon APIs
65 # [no-]zlib     [don't] compile support for zlib compression.
66 # zlib-dynamic  Like "zlib", but the zlib library is expected to be a shared
67 #               library and will be loaded in run-time by the OpenSSL library.
68 # sctp          include SCTP support
69 # enable-weak-ssl-ciphers
70 #               Enable weak ciphers that are disabled by default.
71 # 386           generate 80386 code in assembly modules
72 # no-sse2       disables IA-32 SSE2 code in assembly modules, the above
73 #               mentioned '386' option implies this one
74 # no-<cipher>   build without specified algorithm (rsa, idea, rc5, ...)
75 # -<xxx> +<xxx> compiler options are passed through
76 # -static       while -static is also a pass-through compiler option (and
77 #               as such is limited to environments where it's actually
78 #               meaningful), it triggers a number configuration options,
79 #               namely no-dso, no-pic, no-shared and no-threads. It is
80 #               argued that the only reason to produce statically linked
81 #               binaries (and in context it means executables linked with
82 #               -static flag, and not just executables linked with static
83 #               libcrypto.a) is to eliminate dependency on specific run-time,
84 #               a.k.a. libc version. The mentioned config options are meant
85 #               to achieve just that. Unfortunately on Linux it's impossible
86 #               to eliminate the dependency completely for openssl executable
87 #               because of getaddrinfo and gethostbyname calls, which can
88 #               invoke dynamically loadable library facility anyway to meet
89 #               the lookup requests. For this reason on Linux statically
90 #               linked openssl executable has rather debugging value than
91 #               production quality.
92 #
93 # DEBUG_SAFESTACK use type-safe stacks to enforce type-safety on stack items
94 #               provided to stack calls. Generates unique stack functions for
95 #               each possible stack type.
96 # BN_LLONG      use the type 'long long' in crypto/bn/bn.h
97 # RC4_CHAR      use 'char' instead of 'int' for RC4_INT in crypto/rc4/rc4.h
98 # Following are set automatically by this script
99 #
100 # MD5_ASM       use some extra md5 assembler,
101 # SHA1_ASM      use some extra sha1 assembler, must define L_ENDIAN for x86
102 # RMD160_ASM    use some extra ripemd160 assembler,
103 # SHA256_ASM    sha256_block is implemented in assembler
104 # SHA512_ASM    sha512_block is implemented in assembler
105 # AES_ASM       AES_[en|de]crypt is implemented in assembler
106
107 # Minimum warning options... any contributions to OpenSSL should at least get
108 # past these.
109
110 # DEBUG_UNUSED enables __owur (warn unused result) checks.
111 # -DPEDANTIC complements -pedantic and is meant to mask code that
112 # is not strictly standard-compliant and/or implementation-specific,
113 # e.g. inline assembly, disregards to alignment requirements, such
114 # that -pedantic would complain about. Incidentally -DPEDANTIC has
115 # to be used even in sanitized builds, because sanitizer too is
116 # supposed to and does take notice of non-standard behaviour. Then
117 # -pedantic with pre-C9x compiler would also complain about 'long
118 # long' not being supported. As 64-bit algorithms are common now,
119 # it grew impossible to resolve this without sizeable additional
120 # code, so we just tell compiler to be pedantic about everything
121 # but 'long long' type.
122
123 my $gcc_devteam_warn = "-DDEBUG_UNUSED"
124         . " -DPEDANTIC -pedantic -Wno-long-long"
125         . " -Wall"
126         . " -Wextra"
127         . " -Wno-unused-parameter"
128         . " -Wno-missing-field-initializers"
129         . " -Wswitch"
130         . " -Wsign-compare"
131         . " -Wmissing-prototypes"
132         . " -Wstrict-prototypes"
133         . " -Wshadow"
134         . " -Wformat"
135         . " -Wtype-limits"
136         . " -Wundef"
137         . " -Werror"
138         ;
139
140 # These are used in addition to $gcc_devteam_warn when the compiler is clang.
141 # TODO(openssl-team): fix problems and investigate if (at least) the
142 # following warnings can also be enabled:
143 #       -Wcast-align
144 #       -Wunreachable-code -- no, too ugly/compiler-specific
145 #       -Wlanguage-extension-token -- no, we use asm()
146 #       -Wunused-macros -- no, too tricky for BN and _XOPEN_SOURCE etc
147 #       -Wextended-offsetof -- no, needed in CMS ASN1 code
148 my $clang_devteam_warn = ""
149         . " -Wswitch-default"
150         . " -Wno-parentheses-equality"
151         . " -Wno-language-extension-token"
152         . " -Wno-extended-offsetof"
153         . " -Wconditional-uninitialized"
154         . " -Wincompatible-pointer-types-discards-qualifiers"
155         . " -Wmissing-variable-declarations"
156         . " -Wno-unknown-warning-option"
157         ;
158
159 # This adds backtrace information to the memory leak info.  Is only used
160 # when crypto-mdebug-backtrace is enabled.
161 my $memleak_devteam_backtrace = "-rdynamic";
162
163 my $strict_warnings = 0;
164
165 # As for $BSDthreads. Idea is to maintain "collective" set of flags,
166 # which would cover all BSD flavors. -pthread applies to them all,
167 # but is treated differently. OpenBSD expands is as -D_POSIX_THREAD
168 # -lc_r, which is sufficient. FreeBSD 4.x expands it as -lc_r,
169 # which has to be accompanied by explicit -D_THREAD_SAFE and
170 # sometimes -D_REENTRANT. FreeBSD 5.x expands it as -lc_r, which
171 # seems to be sufficient?
172 our $BSDthreads="-pthread -D_THREAD_SAFE -D_REENTRANT";
173
174 #
175 # API compatibility name to version number mapping.
176 #
177 my $maxapi = "3.0.0";           # API for "no-deprecated" builds
178 my $apitable = {
179     "3.0.0" => 3,
180     "1.1.1" => 2,
181     "1.1.0" => 2,
182     "1.0.2" => 1,
183     "1.0.1" => 1,
184     "1.0.0" => 1,
185     "0.9.8" => 0,
186 };
187
188 our %table = ();
189 our %config = ();
190 our %withargs = ();
191 our $now_printing;      # set to current entry's name in print_table_entry
192                         # (todo: right thing would be to encapsulate name
193                         # into %target [class] and make print_table_entry
194                         # a method)
195
196 # Forward declarations ###############################################
197
198 # read_config(filename)
199 #
200 # Reads a configuration file and populates %table with the contents
201 # (which the configuration file places in %targets).
202 sub read_config;
203
204 # resolve_config(target)
205 #
206 # Resolves all the late evaluations, inheritances and so on for the
207 # chosen target and any target it inherits from.
208 sub resolve_config;
209
210
211 # Information collection #############################################
212
213 # Unified build supports separate build dir
214 my $srcdir = catdir(absolutedir(dirname($0))); # catdir ensures local syntax
215 my $blddir = catdir(absolutedir("."));         # catdir ensures local syntax
216 my $dofile = abs2rel(catfile($srcdir, "util/dofile.pl"));
217
218 my $local_config_envname = 'OPENSSL_LOCAL_CONFIG_DIR';
219
220 $config{sourcedir} = abs2rel($srcdir);
221 $config{builddir} = abs2rel($blddir);
222
223 # Collect reconfiguration information if needed
224 my @argvcopy=@ARGV;
225
226 if (grep /^reconf(igure)?$/, @argvcopy) {
227     die "reconfiguring with other arguments present isn't supported"
228         if scalar @argvcopy > 1;
229     if (-f "./configdata.pm") {
230         my $file = "./configdata.pm";
231         unless (my $return = do $file) {
232             die "couldn't parse $file: $@" if $@;
233             die "couldn't do $file: $!"    unless defined $return;
234             die "couldn't run $file"       unless $return;
235         }
236
237         @argvcopy = defined($configdata::config{perlargv}) ?
238             @{$configdata::config{perlargv}} : ();
239         die "Incorrect data to reconfigure, please do a normal configuration\n"
240             if (grep(/^reconf/,@argvcopy));
241         $config{perlenv} = $configdata::config{perlenv} // {};
242     } else {
243         die "Insufficient data to reconfigure, please do a normal configuration\n";
244     }
245 }
246
247 $config{perlargv} = [ @argvcopy ];
248
249 # Collect version numbers
250 $config{major} = "unknown";
251 $config{minor} = "unknown";
252 $config{patch} = "unknown";
253 $config{prerelease} = "";
254 $config{build_metadata} = "";
255 $config{shlib_version} = "unknown";
256
257 collect_information(
258     collect_from_file(catfile($srcdir,'include/openssl/opensslv.h')),
259     qr/#\s+define\s+OPENSSL_VERSION_MAJOR\s+(\d+)/ =>
260         sub { $config{major} = $1; },
261     qr/#\s+define\s+OPENSSL_VERSION_MINOR\s+(\d+)/ =>
262         sub { $config{minor} = $1; },
263     qr/#\s+define\s+OPENSSL_VERSION_PATCH\s+(\d+)/ =>
264         sub { $config{patch} = $1; },
265     qr/#\s+define\s+OPENSSL_VERSION_PRE_RELEASE\s+"((?:\\.|[^"])*)"/ =>
266         sub { $config{prerelease} = $1; },
267     qr/#\s+define\s+OPENSSL_VERSION_BUILD_METADATA\s+"((?:\\.|[^"])*)"/ =>
268         sub { $config{build_metadata} = $1; },
269     qr/#\s+define\s+OPENSSL_SHLIB_VERSION\s+([\d\.]+)/ =>
270         sub { $config{shlib_version} = $1; },
271     );
272 die "erroneous version information in opensslv.h: ",
273     "$config{major}.$config{minor}.$config{patch}, $config{shlib_version}\n"
274     if ($config{major} eq "unknown"
275             || $config{minor} eq "unknown"
276             || $config{patch} eq "unknown"
277             || $config{shlib_version} eq "unknown");
278
279 # Collect target configurations
280
281 my $pattern = catfile(dirname($0), "Configurations", "*.conf");
282 foreach (sort glob($pattern)) {
283     &read_config($_);
284 }
285
286 if (defined env($local_config_envname)) {
287     if ($^O eq 'VMS') {
288         # VMS environment variables are logical names,
289         # which can be used as is
290         $pattern = $local_config_envname . ':' . '*.conf';
291     } else {
292         $pattern = catfile(env($local_config_envname), '*.conf');
293     }
294
295     foreach (sort glob($pattern)) {
296         &read_config($_);
297     }
298 }
299
300 # Save away perl command information
301 $config{perl_cmd} = $^X;
302 $config{perl_version} = $Config{version};
303 $config{perl_archname} = $Config{archname};
304
305 $config{prefix}="";
306 $config{openssldir}="";
307 $config{processor}="";
308 $config{libdir}="";
309 my $auto_threads=1;    # enable threads automatically? true by default
310 my $default_ranlib;
311
312 # Known TLS and DTLS protocols
313 my @tls = qw(ssl3 tls1 tls1_1 tls1_2 tls1_3);
314 my @dtls = qw(dtls1 dtls1_2);
315
316 # Explicitly known options that are possible to disable.  They can
317 # be regexps, and will be used like this: /^no-${option}$/
318 # For developers: keep it sorted alphabetically
319
320 my @disablables = (
321     "afalgeng",
322     "aria",
323     "asan",
324     "asm",
325     "async",
326     "autoalginit",
327     "autoerrinit",
328     "autoload-config",
329     "bf",
330     "blake2",
331     "camellia",
332     "capieng",
333     "cast",
334     "chacha",
335     "cmac",
336     "cms",
337     "comp",
338     "crypto-mdebug",
339     "crypto-mdebug-backtrace",
340     "ct",
341     "deprecated",
342     "des",
343     "devcryptoeng",
344     "dgram",
345     "dh",
346     "dsa",
347     "dso",
348     "dtls",
349     "dynamic-engine",
350     "ec",
351     "ec2m",
352     "ecdh",
353     "ecdsa",
354     "ec_nistp_64_gcc_128",
355     "egd",
356     "engine",
357     "err",
358     "external-tests",
359     "filenames",
360     "fuzz-libfuzzer",
361     "fuzz-afl",
362     "gost",
363     "heartbeats",
364     "hw(-.+)?",
365     "idea",
366     "makedepend",
367     "md2",
368     "md4",
369     "mdc2",
370     "msan",
371     "multiblock",
372     "nextprotoneg",
373     "ocb",
374     "ocsp",
375     "pic",
376     "poly1305",
377     "posix-io",
378     "psk",
379     "rc2",
380     "rc4",
381     "rc5",
382     "rdrand",
383     "rfc3779",
384     "rmd160",
385     "scrypt",
386     "sctp",
387     "seed",
388     "shared",
389     "siphash",
390     "sm2",
391     "sm3",
392     "sm4",
393     "sock",
394     "srp",
395     "srtp",
396     "sse2",
397     "ssl",
398     "ssl-trace",
399     "static-engine",
400     "stdio",
401     "tests",
402     "threads",
403     "tls",
404     "ts",
405     "ubsan",
406     "ui-console",
407     "unit-test",
408     "whirlpool",
409     "weak-ssl-ciphers",
410     "zlib",
411     "zlib-dynamic",
412     );
413 foreach my $proto ((@tls, @dtls))
414         {
415         push(@disablables, $proto);
416         push(@disablables, "$proto-method") unless $proto eq "tls1_3";
417         }
418
419 my %deprecated_disablables = (
420     "ssl2" => undef,
421     "buf-freelists" => undef,
422     "ripemd" => "rmd160",
423     "ui" => "ui-console",
424     );
425
426 # All of the following are disabled by default:
427
428 our %disabled = ( # "what"         => "comment"
429                   "asan"                => "default",
430                   "crypto-mdebug"       => "default",
431                   "crypto-mdebug-backtrace" => "default",
432                   "devcryptoeng"        => "default",
433                   "ec_nistp_64_gcc_128" => "default",
434                   "egd"                 => "default",
435                   "external-tests"      => "default",
436                   "fuzz-libfuzzer"      => "default",
437                   "fuzz-afl"            => "default",
438                   "heartbeats"          => "default",
439                   "md2"                 => "default",
440                   "msan"                => "default",
441                   "rc5"                 => "default",
442                   "sctp"                => "default",
443                   "ssl-trace"           => "default",
444                   "ssl3"                => "default",
445                   "ssl3-method"         => "default",
446                   "ubsan"               => "default",
447                   "unit-test"           => "default",
448                   "weak-ssl-ciphers"    => "default",
449                   "zlib"                => "default",
450                   "zlib-dynamic"        => "default",
451                 );
452
453 # Note: => pair form used for aesthetics, not to truly make a hash table
454 my @disable_cascades = (
455     # "what"            => [ "cascade", ... ]
456     sub { $config{processor} eq "386" }
457                         => [ "sse2" ],
458     "ssl"               => [ "ssl3" ],
459     "ssl3-method"       => [ "ssl3" ],
460     "zlib"              => [ "zlib-dynamic" ],
461     "des"               => [ "mdc2" ],
462     "ec"                => [ "ecdsa", "ecdh" ],
463
464     "dgram"             => [ "dtls", "sctp" ],
465     "sock"              => [ "dgram" ],
466     "dtls"              => [ @dtls ],
467     sub { 0 == scalar grep { !$disabled{$_} } @dtls }
468                         => [ "dtls" ],
469
470     "tls"               => [ @tls ],
471     sub { 0 == scalar grep { !$disabled{$_} } @tls }
472                         => [ "tls" ],
473
474     "crypto-mdebug"     => [ "crypto-mdebug-backtrace" ],
475
476     # Without DSO, we can't load dynamic engines, so don't build them dynamic
477     "dso"               => [ "dynamic-engine" ],
478
479     # Without position independent code, there can be no shared libraries or DSOs
480     "pic"               => [ "shared" ],
481     "shared"            => [ "dynamic-engine" ],
482     "engine"            => [ "afalgeng", "devcryptoeng" ],
483
484     # no-autoalginit is only useful when building non-shared
485     "autoalginit"       => [ "shared", "apps" ],
486
487     "stdio"             => [ "apps", "capieng", "egd" ],
488     "apps"              => [ "tests" ],
489     "tests"             => [ "external-tests" ],
490     "comp"              => [ "zlib" ],
491     "ec"                => [ "tls1_3", "sm2" ],
492     "sm3"               => [ "sm2" ],
493     sub { !$disabled{"unit-test"} } => [ "heartbeats" ],
494
495     sub { !$disabled{"msan"} } => [ "asm" ],
496     );
497
498 # Avoid protocol support holes.  Also disable all versions below N, if version
499 # N is disabled while N+1 is enabled.
500 #
501 my @list = (reverse @tls);
502 while ((my $first, my $second) = (shift @list, shift @list)) {
503     last unless @list;
504     push @disable_cascades, ( sub { !$disabled{$first} && $disabled{$second} }
505                               => [ @list ] );
506     unshift @list, $second;
507 }
508 my @list = (reverse @dtls);
509 while ((my $first, my $second) = (shift @list, shift @list)) {
510     last unless @list;
511     push @disable_cascades, ( sub { !$disabled{$first} && $disabled{$second} }
512                               => [ @list ] );
513     unshift @list, $second;
514 }
515
516 # Explicit "no-..." options will be collected in %disabled along with the defaults.
517 # To remove something from %disabled, use "enable-foo".
518 # For symmetry, "disable-foo" is a synonym for "no-foo".
519
520 &usage if ($#ARGV < 0);
521
522 # For the "make variables" CINCLUDES and CDEFINES, we support lists with
523 # platform specific list separators.  Users from those platforms should
524 # recognise those separators from how you set up the PATH to find executables.
525 # The default is the Unix like separator, :, but as an exception, we also
526 # support the space as separator.
527 my $list_separator_re =
528     { VMS           => qr/(?<!\^),/,
529       MSWin32       => qr/(?<!\\);/ } -> {$^O} // qr/(?<!\\)[:\s]/;
530 # All the "make variables" we support
531 # Some get pre-populated for the sake of backward compatibility
532 # (we supported those before the change to "make variable" support.
533 my %user = (
534     AR          => env('AR'),
535     ARFLAGS     => [],
536     AS          => undef,
537     ASFLAGS     => [],
538     CC          => env('CC'),
539     CFLAGS      => [],
540     CXX         => env('CXX'),
541     CXXFLAGS    => [],
542     CPP         => undef,
543     CPPFLAGS    => [],  # -D, -I, -Wp,
544     CPPDEFINES  => [],  # Alternative for -D
545     CPPINCLUDES => [],  # Alternative for -I
546     CROSS_COMPILE => env('CROSS_COMPILE'),
547     HASHBANGPERL=> env('HASHBANGPERL') || env('PERL'),
548     LD          => undef,
549     LDFLAGS     => [],  # -L, -Wl,
550     LDLIBS      => [],  # -l
551     MT          => undef,
552     MTFLAGS     => [],
553     PERL        => env('PERL') || ($^O ne "VMS" ? $^X : "perl"),
554     RANLIB      => env('RANLIB'),
555     RC          => env('RC') || env('WINDRES'),
556     RCFLAGS     => [],
557     RM          => undef,
558    );
559 # Info about what "make variables" may be prefixed with the cross compiler
560 # prefix.  This should NEVER mention any such variable with a list for value.
561 my @user_crossable = qw ( AR AS CC CXX CPP LD MT RANLIB RC );
562 # The same but for flags given as Configure options.  These are *additional*
563 # input, as opposed to the VAR=string option that override the corresponding
564 # config target attributes
565 my %useradd = (
566     CPPDEFINES  => [],
567     CPPINCLUDES => [],
568     CPPFLAGS    => [],
569     CFLAGS      => [],
570     CXXFLAGS    => [],
571     LDFLAGS     => [],
572     LDLIBS      => [],
573    );
574
575 my %user_synonyms = (
576     HASHBANGPERL=> 'PERL',
577     RC          => 'WINDRES',
578    );
579
580 # Some target attributes have been renamed, this is the translation table
581 my %target_attr_translate =(
582     ar          => 'AR',
583     as          => 'AS',
584     cc          => 'CC',
585     cxx         => 'CXX',
586     cpp         => 'CPP',
587     hashbangperl => 'HASHBANGPERL',
588     ld          => 'LD',
589     mt          => 'MT',
590     ranlib      => 'RANLIB',
591     rc          => 'RC',
592     rm          => 'RM',
593    );
594
595 # Initialisers coming from 'config' scripts
596 $config{defines} = [ split(/$list_separator_re/, env('__CNF_CPPDEFINES')) ];
597 $config{includes} = [ split(/$list_separator_re/, env('__CNF_CPPINCLUDES')) ];
598 $config{cppflags} = [ env('__CNF_CPPFLAGS') || () ];
599 $config{cflags} = [ env('__CNF_CFLAGS') || () ];
600 $config{cxxflags} = [ env('__CNF_CXXFLAGS') || () ];
601 $config{lflags} = [ env('__CNF_LDFLAGS') || () ];
602 $config{ex_libs} = [ env('__CNF_LDLIBS') || () ];
603
604 $config{openssl_api_defines}=[];
605 $config{openssl_sys_defines}=[];
606 $config{openssl_feature_defines}=[];
607 $config{options}="";
608 $config{build_type} = "release";
609 my $target="";
610
611 my %cmdvars = ();               # Stores FOO='blah' type arguments
612 my %unsupported_options = ();
613 my %deprecated_options = ();
614 # If you change this, update apps/version.c
615 my @known_seed_sources = qw(getrandom devrandom os egd none rdcpu librandom);
616 my @seed_sources = ();
617 while (@argvcopy)
618         {
619         $_ = shift @argvcopy;
620
621         # Support env variable assignments among the options
622         if (m|^(\w+)=(.+)?$|)
623                 {
624                 $cmdvars{$1} = $2;
625                 # Every time a variable is given as a configuration argument,
626                 # it acts as a reset if the variable.
627                 if (exists $user{$1})
628                         {
629                         $user{$1} = ref $user{$1} eq "ARRAY" ? [] : undef;
630                         }
631                 #if (exists $useradd{$1})
632                 #       {
633                 #       $useradd{$1} = [];
634                 #       }
635                 next;
636                 }
637
638         # VMS is a case insensitive environment, and depending on settings
639         # out of our control, we may receive options uppercased.  Let's
640         # downcase at least the part before any equal sign.
641         if ($^O eq "VMS")
642                 {
643                 s/^([^=]*)/lc($1)/e;
644                 }
645
646         # some people just can't read the instructions, clang people have to...
647         s/^-no-(?!integrated-as)/no-/;
648
649         # rewrite some options in "enable-..." form
650         s /^-?-?shared$/enable-shared/;
651         s /^sctp$/enable-sctp/;
652         s /^threads$/enable-threads/;
653         s /^zlib$/enable-zlib/;
654         s /^zlib-dynamic$/enable-zlib-dynamic/;
655
656         if (/^(no|disable|enable)-(.+)$/)
657                 {
658                 my $word = $2;
659                 if (!exists $deprecated_disablables{$word}
660                         && !grep { $word =~ /^${_}$/ } @disablables)
661                         {
662                         $unsupported_options{$_} = 1;
663                         next;
664                         }
665                 }
666         if (/^no-(.+)$/ || /^disable-(.+)$/)
667                 {
668                 foreach my $proto ((@tls, @dtls))
669                         {
670                         if ($1 eq "$proto-method")
671                                 {
672                                 $disabled{"$proto"} = "option($proto-method)";
673                                 last;
674                                 }
675                         }
676                 if ($1 eq "dtls")
677                         {
678                         foreach my $proto (@dtls)
679                                 {
680                                 $disabled{$proto} = "option(dtls)";
681                                 }
682                         $disabled{"dtls"} = "option(dtls)";
683                         }
684                 elsif ($1 eq "ssl")
685                         {
686                         # Last one of its kind
687                         $disabled{"ssl3"} = "option(ssl)";
688                         }
689                 elsif ($1 eq "tls")
690                         {
691                         # XXX: Tests will fail if all SSL/TLS
692                         # protocols are disabled.
693                         foreach my $proto (@tls)
694                                 {
695                                 $disabled{$proto} = "option(tls)";
696                                 }
697                         }
698                 elsif ($1 eq "static-engine")
699                         {
700                         delete $disabled{"dynamic-engine"};
701                         }
702                 elsif ($1 eq "dynamic-engine")
703                         {
704                         $disabled{"dynamic-engine"} = "option";
705                         }
706                 elsif (exists $deprecated_disablables{$1})
707                         {
708                         $deprecated_options{$_} = 1;
709                         if (defined $deprecated_disablables{$1})
710                                 {
711                                 $disabled{$deprecated_disablables{$1}} = "option";
712                                 }
713                         }
714                 else
715                         {
716                         $disabled{$1} = "option";
717                         }
718                 # No longer an automatic choice
719                 $auto_threads = 0 if ($1 eq "threads");
720                 }
721         elsif (/^enable-(.+)$/)
722                 {
723                 if ($1 eq "static-engine")
724                         {
725                         $disabled{"dynamic-engine"} = "option";
726                         }
727                 elsif ($1 eq "dynamic-engine")
728                         {
729                         delete $disabled{"dynamic-engine"};
730                         }
731                 elsif ($1 eq "zlib-dynamic")
732                         {
733                         delete $disabled{"zlib"};
734                         }
735                 my $algo = $1;
736                 delete $disabled{$algo};
737
738                 # No longer an automatic choice
739                 $auto_threads = 0 if ($1 eq "threads");
740                 }
741         elsif (/^--strict-warnings$/)
742                 {
743                 $strict_warnings = 1;
744                 }
745         elsif (/^--debug$/)
746                 {
747                 $config{build_type} = "debug";
748                 }
749         elsif (/^--release$/)
750                 {
751                 $config{build_type} = "release";
752                 }
753         elsif (/^386$/)
754                 { $config{processor}=386; }
755         elsif (/^fips$/)
756                 {
757                 die "FIPS mode not supported\n";
758                 }
759         elsif (/^rsaref$/)
760                 {
761                 # No RSAref support any more since it's not needed.
762                 # The check for the option is there so scripts aren't
763                 # broken
764                 }
765         elsif (/^nofipscanistercheck$/)
766                 {
767                 die "FIPS mode not supported\n";
768                 }
769         elsif (/^[-+]/)
770                 {
771                 if (/^--prefix=(.*)$/)
772                         {
773                         $config{prefix}=$1;
774                         die "Directory given with --prefix MUST be absolute\n"
775                                 unless file_name_is_absolute($config{prefix});
776                         }
777                 elsif (/^--api=(.*)$/)
778                         {
779                         $config{api}=$1;
780                         }
781                 elsif (/^--libdir=(.*)$/)
782                         {
783                         $config{libdir}=$1;
784                         }
785                 elsif (/^--openssldir=(.*)$/)
786                         {
787                         $config{openssldir}=$1;
788                         }
789                 elsif (/^--with-zlib-lib=(.*)$/)
790                         {
791                         $withargs{zlib_lib}=$1;
792                         }
793                 elsif (/^--with-zlib-include=(.*)$/)
794                         {
795                         $withargs{zlib_include}=$1;
796                         }
797                 elsif (/^--with-fuzzer-lib=(.*)$/)
798                         {
799                         $withargs{fuzzer_lib}=$1;
800                         }
801                 elsif (/^--with-fuzzer-include=(.*)$/)
802                         {
803                         $withargs{fuzzer_include}=$1;
804                         }
805                 elsif (/^--with-rand-seed=(.*)$/)
806                         {
807                         foreach my $x (split(m|,|, $1))
808                             {
809                             die "Unknown --with-rand-seed choice $x\n"
810                                 if ! grep { $x eq $_ } @known_seed_sources;
811                             push @seed_sources, $x;
812                             }
813                         }
814                 elsif (/^--cross-compile-prefix=(.*)$/)
815                         {
816                         $user{CROSS_COMPILE}=$1;
817                         }
818                 elsif (/^--config=(.*)$/)
819                         {
820                         read_config $1;
821                         }
822                 elsif (/^-l(.*)$/)
823                         {
824                         push @{$useradd{LDLIBS}}, $_;
825                         }
826                 elsif (/^-framework$/)
827                         {
828                         push @{$useradd{LDLIBS}}, $_, shift(@argvcopy);
829                         }
830                 elsif (/^-L(.*)$/ or /^-Wl,/)
831                         {
832                         push @{$useradd{LDFLAGS}}, $_;
833                         }
834                 elsif (/^-rpath$/ or /^-R$/)
835                         # -rpath is the OSF1 rpath flag
836                         # -R is the old Solaris rpath flag
837                         {
838                         my $rpath = shift(@argvcopy) || "";
839                         $rpath .= " " if $rpath ne "";
840                         push @{$useradd{LDFLAGS}}, $_, $rpath;
841                         }
842                 elsif (/^-static$/)
843                         {
844                         push @{$useradd{LDFLAGS}}, $_;
845                         $disabled{"dso"} = "forced";
846                         $disabled{"pic"} = "forced";
847                         $disabled{"shared"} = "forced";
848                         $disabled{"threads"} = "forced";
849                         }
850                 elsif (/^-D(.*)$/)
851                         {
852                         push @{$useradd{CPPDEFINES}}, $1;
853                         }
854                 elsif (/^-I(.*)$/)
855                         {
856                         push @{$useradd{CPPINCLUDES}}, $1;
857                         }
858                 elsif (/^-Wp,$/)
859                         {
860                         push @{$useradd{CPPFLAGS}}, $1;
861                         }
862                 else    # common if (/^[-+]/), just pass down...
863                         {
864                         $_ =~ s/%([0-9a-f]{1,2})/chr(hex($1))/gei;
865                         push @{$useradd{CFLAGS}}, $_;
866                         push @{$useradd{CXXFLAGS}}, $_;
867                         }
868                 }
869         else
870                 {
871                 die "target already defined - $target (offending arg: $_)\n" if ($target ne "");
872                 $target=$_;
873                 }
874         unless ($_ eq $target || /^no-/ || /^disable-/)
875                 {
876                 # "no-..." follows later after implied deactivations
877                 # have been derived.  (Don't take this too seriously,
878                 # we really only write OPTIONS to the Makefile out of
879                 # nostalgia.)
880
881                 if ($config{options} eq "")
882                         { $config{options} = $_; }
883                 else
884                         { $config{options} .= " ".$_; }
885                 }
886         }
887
888 if (defined($config{api}) && !exists $apitable->{$config{api}}) {
889         die "***** Unsupported api compatibility level: $config{api}\n",
890 }
891
892 if (keys %deprecated_options)
893         {
894         warn "***** Deprecated options: ",
895                 join(", ", keys %deprecated_options), "\n";
896         }
897 if (keys %unsupported_options)
898         {
899         die "***** Unsupported options: ",
900                 join(", ", keys %unsupported_options), "\n";
901         }
902
903 # If any %useradd entry has been set, we must check that the "make
904 # variables" haven't been set.  We start by checking of any %useradd entry
905 # is set.
906 if (grep { scalar @$_ > 0 } values %useradd) {
907     # Hash of env / make variables names.  The possible values are:
908     # 1 - "make vars"
909     # 2 - %useradd entry set
910     # 3 - both set
911     my %detected_vars =
912         map { my $v = 0;
913               $v += 1 if $cmdvars{$_};
914               $v += 2 if @{$useradd{$_}};
915               $_ => $v }
916         keys %useradd;
917
918     # If any of the corresponding "make variables" is set, we error
919     if (grep { $_ & 1 } values %detected_vars) {
920         my $names = join(', ', grep { $detected_vars{$_} > 0 }
921                                sort keys %detected_vars);
922         die <<"_____";
923 ***** Mixing make variables and additional compiler/linker flags as
924 ***** configure command line option is not permitted.
925 ***** Affected make variables: $names
926 _____
927     }
928 }
929
930 # Check through all supported command line variables to see if any of them
931 # were set, and canonicalise the values we got.  If no compiler or linker
932 # flag or anything else that affects %useradd was set, we also check the
933 # environment for values.
934 my $anyuseradd =
935     grep { defined $_ && (ref $_ ne 'ARRAY' || @$_) } values %useradd;
936 foreach (keys %user) {
937     my $value = $cmdvars{$_};
938     $value //= env($_) unless $anyuseradd;
939     $value //=
940         defined $user_synonyms{$_} ? $cmdvars{$user_synonyms{$_}} : undef;
941     $value //= defined $user_synonyms{$_} ? env($user_synonyms{$_}) : undef
942         unless $anyuseradd;
943
944     if (defined $value) {
945         if (ref $user{$_} eq 'ARRAY') {
946             $user{$_} = [ split /$list_separator_re/, $value ];
947         } elsif (!defined $user{$_}) {
948             $user{$_} = $value;
949         }
950     }
951 }
952
953 if (grep { /-rpath\b/ } ($user{LDFLAGS} ? @{$user{LDFLAGS}} : ())
954     && !$disabled{shared}
955     && !($disabled{asan} && $disabled{msan} && $disabled{ubsan})) {
956     die "***** Cannot simultaneously use -rpath, shared libraries, and\n",
957         "***** any of asan, msan or ubsan\n";
958 }
959
960 my @tocheckfor = (keys %disabled);
961 while (@tocheckfor) {
962     my %new_tocheckfor = ();
963     my @cascade_copy = (@disable_cascades);
964     while (@cascade_copy) {
965         my ($test, $descendents) = (shift @cascade_copy, shift @cascade_copy);
966         if (ref($test) eq "CODE" ? $test->() : defined($disabled{$test})) {
967             foreach(grep { !defined($disabled{$_}) } @$descendents) {
968                 $new_tocheckfor{$_} = 1; $disabled{$_} = "forced";
969             }
970         }
971     }
972     @tocheckfor = (keys %new_tocheckfor);
973 }
974
975 our $die = sub { die @_; };
976 if ($target eq "TABLE") {
977     local $die = sub { warn @_; };
978     foreach (sort keys %table) {
979         print_table_entry($_, "TABLE");
980     }
981     exit 0;
982 }
983
984 if ($target eq "LIST") {
985     foreach (sort keys %table) {
986         print $_,"\n" unless $table{$_}->{template};
987     }
988     exit 0;
989 }
990
991 if ($target eq "HASH") {
992     local $die = sub { warn @_; };
993     print "%table = (\n";
994     foreach (sort keys %table) {
995         print_table_entry($_, "HASH");
996     }
997     exit 0;
998 }
999
1000 print "Configuring OpenSSL version $config{version} ($config{version_num}) ";
1001 print "for $target\n";
1002
1003 if (scalar(@seed_sources) == 0) {
1004     print "Using os-specific seed configuration\n";
1005     push @seed_sources, 'os';
1006 }
1007 if (scalar(grep { $_ eq 'none' } @seed_sources) > 0) {
1008     die "Cannot seed with none and anything else" if scalar(@seed_sources) > 1;
1009     warn <<_____ if scalar(@seed_sources) == 1;
1010
1011 ============================== WARNING ===============================
1012 You have selected the --with-rand-seed=none option, which effectively
1013 disables automatic reseeding of the OpenSSL random generator.
1014 All operations depending on the random generator such as creating keys
1015 will not work unless the random generator is seeded manually by the
1016 application.
1017
1018 Please read the 'Note on random number generation' section in the
1019 INSTALL instructions and the RAND_DRBG(7) manual page for more details.
1020 ============================== WARNING ===============================
1021
1022 _____
1023 }
1024 push @{$config{openssl_feature_defines}},
1025      map { (my $x = $_) =~ tr|[\-a-z]|[_A-Z]|; "OPENSSL_RAND_SEED_$x" }
1026         @seed_sources;
1027
1028 # Backward compatibility?
1029 if ($target =~ m/^CygWin32(-.*)$/) {
1030     $target = "Cygwin".$1;
1031 }
1032
1033 # Support for legacy targets having a name starting with 'debug-'
1034 my ($d, $t) = $target =~ m/^(debug-)?(.*)$/;
1035 if ($d) {
1036     $config{build_type} = "debug";
1037
1038     # If we do not find debug-foo in the table, the target is set to foo.
1039     if (!$table{$target}) {
1040         $target = $t;
1041     }
1042 }
1043
1044 &usage if !$table{$target} || $table{$target}->{template};
1045
1046 $config{target} = $target;
1047 my %target = resolve_config($target);
1048
1049 foreach (keys %target_attr_translate) {
1050     $target{$target_attr_translate{$_}} = $target{$_}
1051         if $target{$_};
1052     delete $target{$_};
1053 }
1054
1055 %target = ( %{$table{DEFAULTS}}, %target );
1056
1057 # Make the flags to build DSOs the same as for shared libraries unless they
1058 # are already defined
1059 $target{module_cflags} = $target{shared_cflag} unless defined $target{module_cflags};
1060 $target{module_cxxflags} = $target{shared_cxxflag} unless defined $target{module_cxxflags};
1061 $target{module_ldflags} = $target{shared_ldflag} unless defined $target{module_ldflags};
1062 {
1063     my $shared_info_pl =
1064         catfile(dirname($0), "Configurations", "shared-info.pl");
1065     my %shared_info = read_eval_file($shared_info_pl);
1066     push @{$target{_conf_fname_int}}, $shared_info_pl;
1067     my $si = $target{shared_target};
1068     while (ref $si ne "HASH") {
1069         last if ! defined $si;
1070         if (ref $si eq "CODE") {
1071             $si = $si->();
1072         } else {
1073             $si = $shared_info{$si};
1074         }
1075     }
1076
1077     # Some of the 'shared_target' values don't have any entried in
1078     # %shared_info.  That's perfectly fine, AS LONG AS the build file
1079     # template knows how to handle this.  That is currently the case for
1080     # Windows and VMS.
1081     if (defined $si) {
1082         # Just as above, copy certain shared_* attributes to the corresponding
1083         # module_ attribute unless the latter is already defined
1084         $si->{module_cflags} = $si->{shared_cflag} unless defined $si->{module_cflags};
1085         $si->{module_cxxflags} = $si->{shared_cxxflag} unless defined $si->{module_cxxflags};
1086         $si->{module_ldflags} = $si->{shared_ldflag} unless defined $si->{module_ldflags};
1087         foreach (sort keys %$si) {
1088             $target{$_} = defined $target{$_}
1089                 ? add($si->{$_})->($target{$_})
1090                 : $si->{$_};
1091         }
1092     }
1093 }
1094
1095 my %conf_files = map { $_ => 1 } (@{$target{_conf_fname_int}});
1096 $config{conf_files} = [ sort keys %conf_files ];
1097
1098 foreach my $feature (@{$target{disable}}) {
1099     if (exists $deprecated_disablables{$feature}) {
1100         warn "***** config $target disables deprecated feature $feature\n";
1101     } elsif (!grep { $feature eq $_ } @disablables) {
1102         die "***** config $target disables unknown feature $feature\n";
1103     }
1104     $disabled{$feature} = 'config';
1105 }
1106 foreach my $feature (@{$target{enable}}) {
1107     if ("default" eq ($disabled{$_} // "")) {
1108         if (exists $deprecated_disablables{$feature}) {
1109             warn "***** config $target enables deprecated feature $feature\n";
1110         } elsif (!grep { $feature eq $_ } @disablables) {
1111             die "***** config $target enables unknown feature $feature\n";
1112         }
1113         delete $disabled{$_};
1114     }
1115 }
1116
1117 $target{CXXFLAGS}//=$target{CFLAGS} if $target{CXX};
1118 $target{cxxflags}//=$target{cflags} if $target{CXX};
1119 $target{exe_extension}="";
1120 $target{exe_extension}=".exe" if ($config{target} eq "DJGPP"
1121                                   || $config{target} =~ /^(?:Cygwin|mingw)/);
1122 $target{exe_extension}=".pm"  if ($config{target} =~ /vos/);
1123 $target{def_extension}=".ld";
1124 $target{def_extension}=".def" if $config{target} =~ /^mingw|VC-/;
1125 $target{def_extension}=".opt" if $config{target} =~ /^vms/;
1126 ($target{shared_extension_simple}=$target{shared_extension})
1127     =~ s|\.\$\(SHLIB_VERSION_NUMBER\)||
1128     unless defined($target{shared_extension_simple});
1129 $target{dso_extension}//=$target{shared_extension_simple};
1130 ($target{shared_import_extension}=$target{shared_extension_simple}.".a")
1131     if ($config{target} =~ /^(?:Cygwin|mingw)/);
1132
1133 # Fill %config with values from %user, and in case those are undefined or
1134 # empty, use values from %target (acting as a default).
1135 foreach (keys %user) {
1136     my $ref_type = ref $user{$_};
1137
1138     # Temporary function.  Takes an intended ref type (empty string or "ARRAY")
1139     # and a value that's to be coerced into that type.
1140     my $mkvalue = sub {
1141         my $type = shift;
1142         my $value = shift;
1143         my $undef_p = shift;
1144
1145         die "Too many arguments for \$mkvalue" if @_;
1146
1147         while (ref $value eq 'CODE') {
1148             $value = $value->();
1149         }
1150
1151         if ($type eq 'ARRAY') {
1152             return undef unless defined $value;
1153             return undef if ref $value ne 'ARRAY' && !$value;
1154             return undef if ref $value eq 'ARRAY' && !@$value;
1155             return [ $value ] unless ref $value eq 'ARRAY';
1156         }
1157         return undef unless $value;
1158         return $value;
1159     };
1160
1161     $config{$_} =
1162         $mkvalue->($ref_type, $user{$_})
1163         || $mkvalue->($ref_type, $target{$_});
1164     delete $config{$_} unless defined $config{$_};
1165 }
1166
1167 # Allow overriding the build file name
1168 $config{build_file} = env('BUILDFILE') || $target{build_file} || "Makefile";
1169
1170 ######################################################################
1171 # Build up information for skipping certain directories depending on disabled
1172 # features, as well as setting up macros for disabled features.
1173
1174 # This is a tentative database of directories to skip.  Some entries may not
1175 # correspond to anything real, but that's ok, they will simply be ignored.
1176 # The actual processing of these entries is done in the build.info lookup
1177 # loop further down.
1178 #
1179 # The key is a Unix formated path in the source tree, the value is an index
1180 # into %disabled_info, so any existing path gets added to a corresponding
1181 # 'skipped' entry in there with the list of skipped directories.
1182 my %skipdir = ();
1183 my %disabled_info = ();         # For configdata.pm
1184 foreach my $what (sort keys %disabled) {
1185     $config{options} .= " no-$what";
1186
1187     if (!grep { $what eq $_ } ( 'dso', 'threads', 'shared', 'pic',
1188                                 'dynamic-engine', 'makedepend',
1189                                 'zlib-dynamic', 'zlib', 'sse2' )) {
1190         (my $WHAT = uc $what) =~ s|-|_|g;
1191         my $skipdir = $what;
1192
1193         # fix-up crypto/directory name(s)
1194         $skipdir = "ripemd" if $what eq "rmd160";
1195         $skipdir = "whrlpool" if $what eq "whirlpool";
1196
1197         my $macro = $disabled_info{$what}->{macro} = "OPENSSL_NO_$WHAT";
1198         push @{$config{openssl_feature_defines}}, $macro;
1199
1200         $skipdir{engines} = $what if $what eq 'engine';
1201         $skipdir{"crypto/$skipdir"} = $what
1202             unless $what eq 'async' || $what eq 'err';
1203     }
1204 }
1205
1206 # Make sure build_scheme is consistent.
1207 $target{build_scheme} = [ $target{build_scheme} ]
1208     if ref($target{build_scheme}) ne "ARRAY";
1209
1210 my ($builder, $builder_platform, @builder_opts) =
1211     @{$target{build_scheme}};
1212
1213 foreach my $checker (($builder_platform."-".$target{build_file}."-checker.pm",
1214                       $builder_platform."-checker.pm")) {
1215     my $checker_path = catfile($srcdir, "Configurations", $checker);
1216     if (-f $checker_path) {
1217         my $fn = $ENV{CONFIGURE_CHECKER_WARN}
1218             ? sub { warn $@; } : sub { die $@; };
1219         if (! do $checker_path) {
1220             if ($@) {
1221                 $fn->($@);
1222             } elsif ($!) {
1223                 $fn->($!);
1224             } else {
1225                 $fn->("The detected tools didn't match the platform\n");
1226             }
1227         }
1228         last;
1229     }
1230 }
1231
1232 push @{$config{defines}}, "NDEBUG"    if $config{build_type} eq "release";
1233
1234 if ($target =~ /^mingw/ && `$config{CC} --target-help 2>&1` =~ m/-mno-cygwin/m)
1235         {
1236         push @{$config{cflags}}, "-mno-cygwin";
1237         push @{$config{cxxflags}}, "-mno-cygwin" if $config{CXX};
1238         push @{$config{shared_ldflag}}, "-mno-cygwin";
1239         }
1240
1241 if ($target =~ /linux.*-mips/ && !$disabled{asm}
1242         && !grep { $_ !~ /-m(ips|arch=)/ } (@{$user{CFLAGS}},
1243                                             @{$useradd{CFLAGS}})) {
1244         # minimally required architecture flags for assembly modules
1245         my $value;
1246         $value = '-mips2' if ($target =~ /mips32/);
1247         $value = '-mips3' if ($target =~ /mips64/);
1248         unshift @{$config{cflags}}, $value;
1249         unshift @{$config{cxxflags}}, $value if $config{CXX};
1250 }
1251
1252 # If threads aren't disabled, check how possible they are
1253 unless ($disabled{threads}) {
1254     if ($auto_threads) {
1255         # Enabled by default, disable it forcibly if unavailable
1256         if ($target{thread_scheme} eq "(unknown)") {
1257             $disabled{threads} = "unavailable";
1258         }
1259     } else {
1260         # The user chose to enable threads explicitly, let's see
1261         # if there's a chance that's possible
1262         if ($target{thread_scheme} eq "(unknown)") {
1263             # If the user asked for "threads" and we don't have internal
1264             # knowledge how to do it, [s]he is expected to provide any
1265             # system-dependent compiler options that are necessary.  We
1266             # can't truly check that the given options are correct, but
1267             # we expect the user to know what [s]He is doing.
1268             if (!@{$user{CFLAGS}} && !@{$useradd{CFLAGS}}
1269                     && !@{$user{CPPDEFINES}} && !@{$useradd{CPPDEFINES}}) {
1270                 die "You asked for multi-threading support, but didn't\n"
1271                     ,"provide any system-specific compiler options\n";
1272             }
1273         }
1274     }
1275 }
1276
1277 # If threads still aren't disabled, add a C macro to ensure the source
1278 # code knows about it.  Any other flag is taken care of by the configs.
1279 unless($disabled{threads}) {
1280     push @{$config{openssl_feature_defines}}, "OPENSSL_THREADS";
1281 }
1282
1283 # With "deprecated" disable all deprecated features.
1284 if (defined($disabled{"deprecated"})) {
1285         $config{api} = $maxapi;
1286 }
1287
1288 my $no_shared_warn=0;
1289 if ($target{shared_target} eq "")
1290         {
1291         $no_shared_warn = 1
1292             if (!$disabled{shared} || !$disabled{"dynamic-engine"});
1293         $disabled{shared} = "no-shared-target";
1294         $disabled{pic} = $disabled{shared} = $disabled{"dynamic-engine"} =
1295             "no-shared-target";
1296         }
1297
1298 if ($disabled{"dynamic-engine"}) {
1299         push @{$config{openssl_feature_defines}}, "OPENSSL_NO_DYNAMIC_ENGINE";
1300         $config{dynamic_engines} = 0;
1301 } else {
1302         push @{$config{openssl_feature_defines}}, "OPENSSL_NO_STATIC_ENGINE";
1303         $config{dynamic_engines} = 1;
1304 }
1305
1306 unless ($disabled{asan}) {
1307     push @{$config{cflags}}, "-fsanitize=address";
1308     push @{$config{cxxflags}}, "-fsanitize=address" if $config{CXX};
1309 }
1310
1311 unless ($disabled{ubsan}) {
1312     # -DPEDANTIC or -fnosanitize=alignment may also be required on some
1313     # platforms.
1314     push @{$config{cflags}}, "-fsanitize=undefined", "-fno-sanitize-recover=all";
1315     push @{$config{cxxflags}}, "-fsanitize=undefined", "-fno-sanitize-recover=all"
1316         if $config{CXX};
1317 }
1318
1319 unless ($disabled{msan}) {
1320   push @{$config{cflags}}, "-fsanitize=memory";
1321   push @{$config{cxxflags}}, "-fsanitize=memory" if $config{CXX};
1322 }
1323
1324 unless ($disabled{"fuzz-libfuzzer"} && $disabled{"fuzz-afl"}
1325         && $disabled{asan} && $disabled{ubsan} && $disabled{msan}) {
1326     push @{$config{cflags}}, "-fno-omit-frame-pointer", "-g";
1327     push @{$config{cxxflags}}, "-fno-omit-frame-pointer", "-g" if $config{CXX};
1328 }
1329 #
1330 # Platform fix-ups
1331 #
1332
1333 # This saves the build files from having to check
1334 if ($disabled{pic})
1335         {
1336         foreach (qw(shared_cflag shared_cxxflag shared_cppflag
1337                     shared_defines shared_includes shared_ldflag
1338                     module_cflags module_cxxflags module_cppflags
1339                     module_defines module_includes module_lflags))
1340                 {
1341                 delete $config{$_};
1342                 $target{$_} = "";
1343                 }
1344         }
1345 else
1346         {
1347         push @{$config{lib_defines}}, "OPENSSL_PIC";
1348         }
1349
1350 if ($target{sys_id} ne "")
1351         {
1352         push @{$config{openssl_sys_defines}}, "OPENSSL_SYS_$target{sys_id}";
1353         }
1354
1355 unless ($disabled{asm}) {
1356     $target{cpuid_asm_src}=$table{DEFAULTS}->{cpuid_asm_src} if ($config{processor} eq "386");
1357     push @{$config{lib_defines}}, "OPENSSL_CPUID_OBJ" if ($target{cpuid_asm_src} ne "mem_clr.c");
1358
1359     $target{bn_asm_src} =~ s/\w+-gf2m.c// if (defined($disabled{ec2m}));
1360
1361     # bn-586 is the only one implementing bn_*_part_words
1362     push @{$config{lib_defines}}, "OPENSSL_BN_ASM_PART_WORDS" if ($target{bn_asm_src} =~ /bn-586/);
1363     push @{$config{lib_defines}}, "OPENSSL_IA32_SSE2" if (!$disabled{sse2} && $target{bn_asm_src} =~ /86/);
1364
1365     push @{$config{lib_defines}}, "OPENSSL_BN_ASM_MONT" if ($target{bn_asm_src} =~ /-mont/);
1366     push @{$config{lib_defines}}, "OPENSSL_BN_ASM_MONT5" if ($target{bn_asm_src} =~ /-mont5/);
1367     push @{$config{lib_defines}}, "OPENSSL_BN_ASM_GF2m" if ($target{bn_asm_src} =~ /-gf2m/);
1368     push @{$config{lib_defines}}, "BN_DIV3W" if ($target{bn_asm_src} =~ /-div3w/);
1369
1370     if ($target{sha1_asm_src}) {
1371         push @{$config{lib_defines}}, "SHA1_ASM"   if ($target{sha1_asm_src} =~ /sx86/ || $target{sha1_asm_src} =~ /sha1/);
1372         push @{$config{lib_defines}}, "SHA256_ASM" if ($target{sha1_asm_src} =~ /sha256/);
1373         push @{$config{lib_defines}}, "SHA512_ASM" if ($target{sha1_asm_src} =~ /sha512/);
1374     }
1375     if ($target{keccak1600_asm_src} ne $table{DEFAULTS}->{keccak1600_asm_src}) {
1376         push @{$config{lib_defines}}, "KECCAK1600_ASM";
1377     }
1378     if ($target{rc4_asm_src} ne $table{DEFAULTS}->{rc4_asm_src}) {
1379         push @{$config{lib_defines}}, "RC4_ASM";
1380     }
1381     if ($target{md5_asm_src}) {
1382         push @{$config{lib_defines}}, "MD5_ASM";
1383     }
1384     $target{cast_asm_src}=$table{DEFAULTS}->{cast_asm_src} unless $disabled{pic}; # CAST assembler is not PIC
1385     if ($target{rmd160_asm_src}) {
1386         push @{$config{lib_defines}}, "RMD160_ASM";
1387     }
1388     if ($target{aes_asm_src}) {
1389         push @{$config{lib_defines}}, "AES_ASM" if ($target{aes_asm_src} =~ m/\baes-/);;
1390         # aes-ctr.fake is not a real file, only indication that assembler
1391         # module implements AES_ctr32_encrypt...
1392         push @{$config{lib_defines}}, "AES_CTR_ASM" if ($target{aes_asm_src} =~ s/\s*aes-ctr\.fake//);
1393         # aes-xts.fake indicates presence of AES_xts_[en|de]crypt...
1394         push @{$config{lib_defines}}, "AES_XTS_ASM" if ($target{aes_asm_src} =~ s/\s*aes-xts\.fake//);
1395         $target{aes_asm_src} =~ s/\s*(vpaes|aesni)-x86\.s//g if ($disabled{sse2});
1396         push @{$config{lib_defines}}, "VPAES_ASM" if ($target{aes_asm_src} =~ m/vpaes/);
1397         push @{$config{lib_defines}}, "BSAES_ASM" if ($target{aes_asm_src} =~ m/bsaes/);
1398     }
1399     if ($target{wp_asm_src} =~ /mmx/) {
1400         if ($config{processor} eq "386") {
1401             $target{wp_asm_src}=$table{DEFAULTS}->{wp_asm_src};
1402         } elsif (!$disabled{"whirlpool"}) {
1403             push @{$config{lib_defines}}, "WHIRLPOOL_ASM";
1404         }
1405     }
1406     if ($target{modes_asm_src} =~ /ghash-/) {
1407         push @{$config{lib_defines}}, "GHASH_ASM";
1408     }
1409     if ($target{ec_asm_src} =~ /ecp_nistz256/) {
1410         push @{$config{lib_defines}}, "ECP_NISTZ256_ASM";
1411     }
1412     if ($target{ec_asm_src} =~ /x25519/) {
1413         push @{$config{lib_defines}}, "X25519_ASM";
1414     }
1415     if ($target{padlock_asm_src} ne $table{DEFAULTS}->{padlock_asm_src}) {
1416         push @{$config{lib_defines}}, "PADLOCK_ASM";
1417     }
1418     if ($target{poly1305_asm_src} ne "") {
1419         push @{$config{lib_defines}}, "POLY1305_ASM";
1420     }
1421 }
1422
1423 my %predefined = compiler_predefined($config{CROSS_COMPILE}.$config{CC});
1424
1425 # Check for makedepend capabilities.
1426 if (!$disabled{makedepend}) {
1427     if ($config{target} =~ /^(VC|vms)-/) {
1428         # For VC- and vms- targets, there's nothing more to do here.  The
1429         # functionality is hard coded in the corresponding build files for
1430         # cl (Windows) and CC/DECC (VMS).
1431     } elsif (($predefined{__GNUC__} // -1) >= 3
1432              && !($predefined{__APPLE_CC__} && !$predefined{__clang__})) {
1433         # We know that GNU C version 3 and up as well as all clang
1434         # versions support dependency generation, but Xcode did not
1435         # handle $cc -M before clang support (but claims __GNUC__ = 3)
1436         $config{makedepprog} = "\$(CROSS_COMPILE)$config{CC}";
1437     } else {
1438         # In all other cases, we look for 'makedepend', and disable the
1439         # capability if not found.
1440         $config{makedepprog} = which('makedepend');
1441         $disabled{makedepend} = "unavailable" unless $config{makedepprog};
1442     }
1443 }
1444
1445 if (!$disabled{asm} && !$predefined{__MACH__} && $^O ne 'VMS') {
1446     # probe for -Wa,--noexecstack option...
1447     if ($predefined{__clang__}) {
1448         # clang has builtin assembler, which doesn't recognize --help,
1449         # but it apparently recognizes the option in question on all
1450         # supported platforms even when it's meaningless. In other words
1451         # probe would fail, but probed option always accepted...
1452         push @{$config{cflags}}, "-Wa,--noexecstack", "-Qunused-arguments";
1453     } else {
1454         my $cc = $config{CROSS_COMPILE}.$config{CC};
1455         open(PIPE, "$cc -Wa,--help -c -o null.$$.o -x assembler /dev/null 2>&1 |");
1456         while(<PIPE>) {
1457             if (m/--noexecstack/) {
1458                 push @{$config{cflags}}, "-Wa,--noexecstack";
1459                 last;
1460             }
1461         }
1462         close(PIPE);
1463         unlink("null.$$.o");
1464     }
1465 }
1466
1467 # Deal with bn_ops ###################################################
1468
1469 $config{bn_ll}                  =0;
1470 $config{export_var_as_fn}       =0;
1471 my $def_int="unsigned int";
1472 $config{rc4_int}                =$def_int;
1473 ($config{b64l},$config{b64},$config{b32})=(0,0,1);
1474
1475 my $count = 0;
1476 foreach (sort split(/\s+/,$target{bn_ops})) {
1477     $count++ if /SIXTY_FOUR_BIT|SIXTY_FOUR_BIT_LONG|THIRTY_TWO_BIT/;
1478     $config{export_var_as_fn}=1                 if $_ eq 'EXPORT_VAR_AS_FN';
1479     $config{bn_ll}=1                            if $_ eq 'BN_LLONG';
1480     $config{rc4_int}="unsigned char"            if $_ eq 'RC4_CHAR';
1481     ($config{b64l},$config{b64},$config{b32})
1482         =(0,1,0)                                if $_ eq 'SIXTY_FOUR_BIT';
1483     ($config{b64l},$config{b64},$config{b32})
1484         =(1,0,0)                                if $_ eq 'SIXTY_FOUR_BIT_LONG';
1485     ($config{b64l},$config{b64},$config{b32})
1486         =(0,0,1)                                if $_ eq 'THIRTY_TWO_BIT';
1487 }
1488 die "Exactly one of SIXTY_FOUR_BIT|SIXTY_FOUR_BIT_LONG|THIRTY_TWO_BIT can be set in bn_ops\n"
1489     if $count > 1;
1490
1491
1492 # Hack cflags for better warnings (dev option) #######################
1493
1494 # "Stringify" the C and C++ flags string.  This permits it to be made part of
1495 # a string and works as well on command lines.
1496 $config{cflags} = [ map { (my $x = $_) =~ s/([\\\"])/\\$1/g; $x }
1497                         @{$config{cflags}} ];
1498 $config{cxxflags} = [ map { (my $x = $_) =~ s/([\\\"])/\\$1/g; $x }
1499                           @{$config{cxxflags}} ] if $config{CXX};
1500
1501 $config{openssl_api_defines} = [
1502     "OPENSSL_MIN_API=".($apitable->{$config{api} // ""} // -1)
1503 ];
1504
1505 if ($strict_warnings)
1506         {
1507         my $wopt;
1508         my $gccver = $predefined{__GNUC__} // -1;
1509
1510         die "ERROR --strict-warnings requires gcc[>=4] or gcc-alike"
1511             unless $gccver >= 4;
1512         foreach $wopt (split /\s+/, $gcc_devteam_warn)
1513                 {
1514                 push @{$config{cflags}}, $wopt
1515                         unless grep { $_ eq $wopt } @{$config{cflags}};
1516                 push @{$config{cxxflags}}, $wopt
1517                         if ($config{CXX}
1518                             && !grep { $_ eq $wopt } @{$config{cxxflags}});
1519                 }
1520         if (defined($predefined{__clang__}))
1521                 {
1522                 foreach $wopt (split /\s+/, $clang_devteam_warn)
1523                         {
1524                         push @{$config{cflags}}, $wopt
1525                                 unless grep { $_ eq $wopt } @{$config{cflags}};
1526                         push @{$config{cxxflags}}, $wopt
1527                                 if ($config{CXX}
1528                                     && !grep { $_ eq $wopt } @{$config{cxxflags}});
1529                         }
1530                 }
1531         }
1532
1533 unless ($disabled{"crypto-mdebug-backtrace"})
1534         {
1535         foreach my $wopt (split /\s+/, $memleak_devteam_backtrace)
1536                 {
1537                 push @{$config{cflags}}, $wopt
1538                         unless grep { $_ eq $wopt } @{$config{cflags}};
1539                 push @{$config{cxxflags}}, $wopt
1540                         if ($config{CXX}
1541                             && !grep { $_ eq $wopt } @{$config{cxxflags}});
1542                 }
1543         if ($target =~ /^BSD-/)
1544                 {
1545                 push @{$config{ex_libs}}, "-lexecinfo";
1546                 }
1547         }
1548
1549 unless ($disabled{afalgeng}) {
1550     $config{afalgeng}="";
1551     if (grep { $_ eq 'afalgeng' } @{$target{enable}}) {
1552         my $minver = 4*10000 + 1*100 + 0;
1553         if ($config{CROSS_COMPILE} eq "") {
1554             my $verstr = `uname -r`;
1555             my ($ma, $mi1, $mi2) = split("\\.", $verstr);
1556             ($mi2) = $mi2 =~ /(\d+)/;
1557             my $ver = $ma*10000 + $mi1*100 + $mi2;
1558             if ($ver < $minver) {
1559                 $disabled{afalgeng} = "too-old-kernel";
1560             } else {
1561                 push @{$config{engdirs}}, "afalg";
1562             }
1563         } else {
1564             $disabled{afalgeng} = "cross-compiling";
1565         }
1566     } else {
1567         $disabled{afalgeng}  = "not-linux";
1568     }
1569 }
1570
1571 push @{$config{openssl_feature_defines}}, "OPENSSL_NO_AFALGENG" if ($disabled{afalgeng});
1572
1573 # Finish up %config by appending things the user gave us on the command line
1574 # apart from "make variables"
1575 foreach (keys %useradd) {
1576     # The must all be lists, so we assert that here
1577     die "internal error: \$useradd{$_} isn't an ARRAY\n"
1578         unless ref $useradd{$_} eq 'ARRAY';
1579
1580     if (defined $config{$_}) {
1581         push @{$config{$_}}, @{$useradd{$_}};
1582     } else {
1583         $config{$_} = [ @{$useradd{$_}} ];
1584     }
1585 }
1586
1587 # ALL MODIFICATIONS TO %config and %target MUST BE DONE FROM HERE ON
1588
1589 # If we use the unified build, collect information from build.info files
1590 my %unified_info = ();
1591
1592 my $buildinfo_debug = defined($ENV{CONFIGURE_DEBUG_BUILDINFO});
1593 if ($builder eq "unified") {
1594     use with_fallback qw(Text::Template);
1595
1596     sub cleandir {
1597         my $base = shift;
1598         my $dir = shift;
1599         my $relativeto = shift || ".";
1600
1601         $dir = catdir($base,$dir) unless isabsolute($dir);
1602
1603         # Make sure the directories we're building in exists
1604         mkpath($dir);
1605
1606         my $res = abs2rel(absolutedir($dir), rel2abs($relativeto));
1607         #print STDERR "DEBUG[cleandir]: $dir , $base => $res\n";
1608         return $res;
1609     }
1610
1611     sub cleanfile {
1612         my $base = shift;
1613         my $file = shift;
1614         my $relativeto = shift || ".";
1615
1616         $file = catfile($base,$file) unless isabsolute($file);
1617
1618         my $d = dirname($file);
1619         my $f = basename($file);
1620
1621         # Make sure the directories we're building in exists
1622         mkpath($d);
1623
1624         my $res = abs2rel(catfile(absolutedir($d), $f), rel2abs($relativeto));
1625         #print STDERR "DEBUG[cleanfile]: $d , $f => $res\n";
1626         return $res;
1627     }
1628
1629     # Store the name of the template file we will build the build file from
1630     # in %config.  This may be useful for the build file itself.
1631     my @build_file_template_names =
1632         ( $builder_platform."-".$target{build_file}.".tmpl",
1633           $target{build_file}.".tmpl" );
1634     my @build_file_templates = ();
1635
1636     # First, look in the user provided directory, if given
1637     if (defined env($local_config_envname)) {
1638         @build_file_templates =
1639             map {
1640                 if ($^O eq 'VMS') {
1641                     # VMS environment variables are logical names,
1642                     # which can be used as is
1643                     $local_config_envname . ':' . $_;
1644                 } else {
1645                     catfile(env($local_config_envname), $_);
1646                 }
1647             }
1648             @build_file_template_names;
1649     }
1650     # Then, look in our standard directory
1651     push @build_file_templates,
1652         ( map { cleanfile($srcdir, catfile("Configurations", $_), $blddir) }
1653           @build_file_template_names );
1654
1655     my $build_file_template;
1656     for $_ (@build_file_templates) {
1657         $build_file_template = $_;
1658         last if -f $build_file_template;
1659
1660         $build_file_template = undef;
1661     }
1662     if (!defined $build_file_template) {
1663         die "*** Couldn't find any of:\n", join("\n", @build_file_templates), "\n";
1664     }
1665     $config{build_file_templates}
1666       = [ cleanfile($srcdir, catfile("Configurations", "common0.tmpl"),
1667                     $blddir),
1668           $build_file_template,
1669           cleanfile($srcdir, catfile("Configurations", "common.tmpl"),
1670                     $blddir) ];
1671
1672     my @build_dirs = ( [ ] );   # current directory
1673
1674     $config{build_infos} = [ ];
1675
1676     my %ordinals = ();
1677     while (@build_dirs) {
1678         my @curd = @{shift @build_dirs};
1679         my $sourced = catdir($srcdir, @curd);
1680         my $buildd = catdir($blddir, @curd);
1681
1682         my $unixdir = join('/', @curd);
1683         if (exists $skipdir{$unixdir}) {
1684             my $what = $skipdir{$unixdir};
1685             push @{$disabled_info{$what}->{skipped}}, catdir(@curd);
1686             next;
1687         }
1688
1689         mkpath($buildd);
1690
1691         my $f = 'build.info';
1692         # The basic things we're trying to build
1693         my @programs = ();
1694         my @programs_install = ();
1695         my @libraries = ();
1696         my @libraries_install = ();
1697         my @engines = ();
1698         my @engines_install = ();
1699         my @scripts = ();
1700         my @scripts_install = ();
1701         my @extra = ();
1702         my @overrides = ();
1703         my @intermediates = ();
1704         my @rawlines = ();
1705
1706         my %sources = ();
1707         my %shared_sources = ();
1708         my %includes = ();
1709         my %defines = ();
1710         my %depends = ();
1711         my %renames = ();
1712         my %sharednames = ();
1713         my %generate = ();
1714
1715         # We want to detect configdata.pm in the source tree, so we
1716         # don't use it if the build tree is different.
1717         my $src_configdata = cleanfile($srcdir, "configdata.pm", $blddir);
1718
1719         push @{$config{build_infos}}, catfile(abs2rel($sourced, $blddir), $f);
1720         my $template =
1721             Text::Template->new(TYPE => 'FILE',
1722                                 SOURCE => catfile($sourced, $f),
1723                                 PREPEND => qq{use lib "$FindBin::Bin/util/perl";});
1724         die "Something went wrong with $sourced/$f: $!\n" unless $template;
1725         my @text =
1726             split /^/m,
1727             $template->fill_in(HASH => { config => \%config,
1728                                          target => \%target,
1729                                          disabled => \%disabled,
1730                                          withargs => \%withargs,
1731                                          builddir => abs2rel($buildd, $blddir),
1732                                          sourcedir => abs2rel($sourced, $blddir),
1733                                          buildtop => abs2rel($blddir, $blddir),
1734                                          sourcetop => abs2rel($srcdir, $blddir) },
1735                                DELIMITERS => [ "{-", "-}" ]);
1736
1737         # The top item of this stack has the following values
1738         # -2 positive already run and we found ELSE (following ELSIF should fail)
1739         # -1 positive already run (skip until ENDIF)
1740         # 0 negatives so far (if we're at a condition, check it)
1741         # 1 last was positive (don't skip lines until next ELSE, ELSIF or ENDIF)
1742         # 2 positive ELSE (following ELSIF should fail)
1743         my @skip = ();
1744         collect_information(
1745             collect_from_array([ @text ],
1746                                qr/\\$/ => sub { my $l1 = shift; my $l2 = shift;
1747                                                 $l1 =~ s/\\$//; $l1.$l2 }),
1748             # Info we're looking for
1749             qr/^\s*IF\[((?:\\.|[^\\\]])*)\]\s*$/
1750             => sub {
1751                 if (! @skip || $skip[$#skip] > 0) {
1752                     push @skip, !! $1;
1753                 } else {
1754                     push @skip, -1;
1755                 }
1756             },
1757             qr/^\s*ELSIF\[((?:\\.|[^\\\]])*)\]\s*$/
1758             => sub { die "ELSIF out of scope" if ! @skip;
1759                      die "ELSIF following ELSE" if abs($skip[$#skip]) == 2;
1760                      $skip[$#skip] = -1 if $skip[$#skip] != 0;
1761                      $skip[$#skip] = !! $1
1762                          if $skip[$#skip] == 0; },
1763             qr/^\s*ELSE\s*$/
1764             => sub { die "ELSE out of scope" if ! @skip;
1765                      $skip[$#skip] = -2 if $skip[$#skip] != 0;
1766                      $skip[$#skip] = 2 if $skip[$#skip] == 0; },
1767             qr/^\s*ENDIF\s*$/
1768             => sub { die "ENDIF out of scope" if ! @skip;
1769                      pop @skip; },
1770             qr/^\s*SUBDIRS\s*=\s*(.*)\s*$/
1771             => sub {
1772                 if (!@skip || $skip[$#skip] > 0) {
1773                     foreach (tokenize($1)) {
1774                         push @build_dirs, [ @curd, splitdir($_, 1) ];
1775                     }
1776                 }
1777             },
1778             qr/^\s*PROGRAMS(_NO_INST)?\s*=\s*(.*)\s*$/
1779             => sub {
1780                 if (!@skip || $skip[$#skip] > 0) {
1781                     my $install = $1;
1782                     my @x = tokenize($2);
1783                     push @programs, @x;
1784                     push @programs_install, @x unless $install;
1785                 }
1786             },
1787             qr/^\s*LIBS(_NO_INST)?\s*=\s*(.*)\s*$/
1788             => sub {
1789                 if (!@skip || $skip[$#skip] > 0) {
1790                     my $install = $1;
1791                     my @x = tokenize($2);
1792                     push @libraries, @x;
1793                     push @libraries_install, @x unless $install;
1794                 }
1795             },
1796             qr/^\s*ENGINES(_NO_INST)?\s*=\s*(.*)\s*$/
1797             => sub {
1798                 if (!@skip || $skip[$#skip] > 0) {
1799                     my $install = $1;
1800                     my @x = tokenize($2);
1801                     push @engines, @x;
1802                     push @engines_install, @x unless $install;
1803                 }
1804             },
1805             qr/^\s*SCRIPTS(_NO_INST)?\s*=\s*(.*)\s*$/
1806             => sub {
1807                 if (!@skip || $skip[$#skip] > 0) {
1808                     my $install = $1;
1809                     my @x = tokenize($2);
1810                     push @scripts, @x;
1811                     push @scripts_install, @x unless $install;
1812                 }
1813             },
1814             qr/^\s*EXTRA\s*=\s*(.*)\s*$/
1815             => sub { push @extra, tokenize($1)
1816                          if !@skip || $skip[$#skip] > 0 },
1817             qr/^\s*OVERRIDES\s*=\s*(.*)\s*$/
1818             => sub { push @overrides, tokenize($1)
1819                          if !@skip || $skip[$#skip] > 0 },
1820
1821             qr/^\s*ORDINALS\[((?:\\.|[^\\\]])+)\]\s*=\s*(.*)\s*$/,
1822             => sub { push @{$ordinals{$1}}, tokenize($2)
1823                          if !@skip || $skip[$#skip] > 0 },
1824             qr/^\s*SOURCE\[((?:\\.|[^\\\]])+)\]\s*=\s*(.*)\s*$/
1825             => sub { push @{$sources{$1}}, tokenize($2)
1826                          if !@skip || $skip[$#skip] > 0 },
1827             qr/^\s*SHARED_SOURCE\[((?:\\.|[^\\\]])+)\]\s*=\s*(.*)\s*$/
1828             => sub { push @{$shared_sources{$1}}, tokenize($2)
1829                          if !@skip || $skip[$#skip] > 0 },
1830             qr/^\s*INCLUDE\[((?:\\.|[^\\\]])+)\]\s*=\s*(.*)\s*$/
1831             => sub { push @{$includes{$1}}, tokenize($2)
1832                          if !@skip || $skip[$#skip] > 0 },
1833             qr/^\s*DEFINE\[((?:\\.|[^\\\]])+)\]\s*=\s*(.*)\s*$/
1834             => sub { push @{$defines{$1}}, tokenize($2)
1835                          if !@skip || $skip[$#skip] > 0 },
1836             qr/^\s*DEPEND\[((?:\\.|[^\\\]])*)\]\s*=\s*(.*)\s*$/
1837             => sub { push @{$depends{$1}}, tokenize($2)
1838                          if !@skip || $skip[$#skip] > 0 },
1839             qr/^\s*GENERATE\[((?:\\.|[^\\\]])+)\]\s*=\s*(.*)\s*$/
1840             => sub { push @{$generate{$1}}, $2
1841                          if !@skip || $skip[$#skip] > 0 },
1842             qr/^\s*RENAME\[((?:\\.|[^\\\]])+)\]\s*=\s*(.*)\s*$/
1843             => sub { push @{$renames{$1}}, tokenize($2)
1844                          if !@skip || $skip[$#skip] > 0 },
1845             qr/^\s*SHARED_NAME\[((?:\\.|[^\\\]])+)\]\s*=\s*(.*)\s*$/
1846             => sub { push @{$sharednames{$1}}, tokenize($2)
1847                          if !@skip || $skip[$#skip] > 0 },
1848             qr/^\s*BEGINRAW\[((?:\\.|[^\\\]])+)\]\s*$/
1849             => sub {
1850                 my $lineiterator = shift;
1851                 my $target_kind = $1;
1852                 while (defined $lineiterator->()) {
1853                     s|\R$||;
1854                     if (/^\s*ENDRAW\[((?:\\.|[^\\\]])+)\]\s*$/) {
1855                         die "ENDRAW doesn't match BEGINRAW"
1856                             if $1 ne $target_kind;
1857                         last;
1858                     }
1859                     next if @skip && $skip[$#skip] <= 0;
1860                     push @rawlines,  $_
1861                         if ($target_kind eq $target{build_file}
1862                             || $target_kind eq $target{build_file}."(".$builder_platform.")");
1863                 }
1864             },
1865             qr/^\s*(?:#.*)?$/ => sub { },
1866             "OTHERWISE" => sub { die "Something wrong with this line:\n$_\nat $sourced/$f" },
1867             "BEFORE" => sub {
1868                 if ($buildinfo_debug) {
1869                     print STDERR "DEBUG: Parsing ",join(" ", @_),"\n";
1870                     print STDERR "DEBUG: ... before parsing, skip stack is ",join(" ", map { int($_) } @skip),"\n";
1871                 }
1872             },
1873             "AFTER" => sub {
1874                 if ($buildinfo_debug) {
1875                     print STDERR "DEBUG: .... after parsing, skip stack is ",join(" ", map { int($_) } @skip),"\n";
1876                 }
1877             },
1878             );
1879         die "runaway IF?" if (@skip);
1880
1881         foreach (keys %renames) {
1882             die "$_ renamed to more than one thing: "
1883                 ,join(" ", @{$renames{$_}}),"\n"
1884                 if scalar @{$renames{$_}} > 1;
1885             my $dest = cleanfile($buildd, $_, $blddir);
1886             my $to = cleanfile($buildd, $renames{$_}->[0], $blddir);
1887             die "$dest renamed to more than one thing: "
1888                 ,$unified_info{rename}->{$dest}, $to
1889                 unless !defined($unified_info{rename}->{$dest})
1890                 or $unified_info{rename}->{$dest} eq $to;
1891             $unified_info{rename}->{$dest} = $to;
1892         }
1893
1894         foreach (@programs) {
1895             my $program = cleanfile($buildd, $_, $blddir);
1896             if ($unified_info{rename}->{$program}) {
1897                 $program = $unified_info{rename}->{$program};
1898             }
1899             $unified_info{programs}->{$program} = 1;
1900         }
1901
1902         foreach (@programs_install) {
1903             my $program = cleanfile($buildd, $_, $blddir);
1904             if ($unified_info{rename}->{$program}) {
1905                 $program = $unified_info{rename}->{$program};
1906             }
1907             $unified_info{install}->{programs}->{$program} = 1;
1908         }
1909
1910         foreach (@libraries) {
1911             my $library = cleanfile($buildd, $_, $blddir);
1912             if ($unified_info{rename}->{$library}) {
1913                 $library = $unified_info{rename}->{$library};
1914             }
1915             $unified_info{libraries}->{$library} = 1;
1916         }
1917
1918         foreach (@libraries_install) {
1919             my $library = cleanfile($buildd, $_, $blddir);
1920             if ($unified_info{rename}->{$library}) {
1921                 $library = $unified_info{rename}->{$library};
1922             }
1923             $unified_info{install}->{libraries}->{$library} = 1;
1924         }
1925
1926         die <<"EOF" if scalar @engines and !$config{dynamic_engines};
1927 ENGINES can only be used if configured with 'dynamic-engine'.
1928 This is usually a fault in a build.info file.
1929 EOF
1930         foreach (@engines) {
1931             my $library = cleanfile($buildd, $_, $blddir);
1932             if ($unified_info{rename}->{$library}) {
1933                 $library = $unified_info{rename}->{$library};
1934             }
1935             $unified_info{engines}->{$library} = 1;
1936         }
1937
1938         foreach (@engines_install) {
1939             my $library = cleanfile($buildd, $_, $blddir);
1940             if ($unified_info{rename}->{$library}) {
1941                 $library = $unified_info{rename}->{$library};
1942             }
1943             $unified_info{install}->{engines}->{$library} = 1;
1944         }
1945
1946         foreach (@scripts) {
1947             my $script = cleanfile($buildd, $_, $blddir);
1948             if ($unified_info{rename}->{$script}) {
1949                 $script = $unified_info{rename}->{$script};
1950             }
1951             $unified_info{scripts}->{$script} = 1;
1952         }
1953
1954         foreach (@scripts_install) {
1955             my $script = cleanfile($buildd, $_, $blddir);
1956             if ($unified_info{rename}->{$script}) {
1957                 $script = $unified_info{rename}->{$script};
1958             }
1959             $unified_info{install}->{scripts}->{$script} = 1;
1960         }
1961
1962         foreach (@extra) {
1963             my $extra = cleanfile($buildd, $_, $blddir);
1964             $unified_info{extra}->{$extra} = 1;
1965         }
1966
1967         foreach (@overrides) {
1968             my $override = cleanfile($buildd, $_, $blddir);
1969             $unified_info{overrides}->{$override} = 1;
1970         }
1971
1972         push @{$unified_info{rawlines}}, @rawlines;
1973
1974         unless ($disabled{shared}) {
1975             # Check sharednames.
1976             foreach (keys %sharednames) {
1977                 my $dest = cleanfile($buildd, $_, $blddir);
1978                 if ($unified_info{rename}->{$dest}) {
1979                     $dest = $unified_info{rename}->{$dest};
1980                 }
1981                 die "shared_name for $dest with multiple values: "
1982                     ,join(" ", @{$sharednames{$_}}),"\n"
1983                     if scalar @{$sharednames{$_}} > 1;
1984                 my $to = cleanfile($buildd, $sharednames{$_}->[0], $blddir);
1985                 die "shared_name found for a library $dest that isn't defined\n"
1986                     unless $unified_info{libraries}->{$dest};
1987                 die "shared_name for $dest with multiple values: "
1988                     ,$unified_info{sharednames}->{$dest}, ", ", $to
1989                     unless !defined($unified_info{sharednames}->{$dest})
1990                     or $unified_info{sharednames}->{$dest} eq $to;
1991                 $unified_info{sharednames}->{$dest} = $to;
1992             }
1993
1994             # Additionally, we set up sharednames for libraries that don't
1995             # have any, as themselves.  Only for libraries that aren't
1996             # explicitly static.
1997             foreach (grep !/\.a$/, keys %{$unified_info{libraries}}) {
1998                 if (!defined $unified_info{sharednames}->{$_}) {
1999                     $unified_info{sharednames}->{$_} = $_
2000                 }
2001             }
2002
2003             # Check that we haven't defined any library as both shared and
2004             # explicitly static.  That is forbidden.
2005             my @doubles = ();
2006             foreach (grep /\.a$/, keys %{$unified_info{libraries}}) {
2007                 (my $l = $_) =~ s/\.a$//;
2008                 push @doubles, $l if defined $unified_info{sharednames}->{$l};
2009             }
2010             die "these libraries are both explicitly static and shared:\n  ",
2011                 join(" ", @doubles), "\n"
2012                 if @doubles;
2013         }
2014
2015         foreach (keys %sources) {
2016             my $dest = $_;
2017             my $ddest = cleanfile($buildd, $_, $blddir);
2018             if ($unified_info{rename}->{$ddest}) {
2019                 $ddest = $unified_info{rename}->{$ddest};
2020             }
2021             foreach (@{$sources{$dest}}) {
2022                 my $s = cleanfile($sourced, $_, $blddir);
2023
2024                 # If it isn't in the source tree, we assume it's generated
2025                 # in the build tree
2026                 if ($s eq $src_configdata || ! -f $s || $generate{$_}) {
2027                     $s = cleanfile($buildd, $_, $blddir);
2028                 }
2029                 # We recognise C++, C and asm files
2030                 if ($s =~ /\.(cc|cpp|c|s|S)$/) {
2031                     my $o = $_;
2032                     $o =~ s/\.[csS]$/.o/; # C and assembler
2033                     $o =~ s/\.(cc|cpp)$/_cc.o/; # C++
2034                     $o = cleanfile($buildd, $o, $blddir);
2035                     $unified_info{sources}->{$ddest}->{$o} = -1;
2036                     $unified_info{sources}->{$o}->{$s} = -1;
2037                 } elsif ($s =~ /\.rc$/) {
2038                     # We also recognise resource files
2039                     my $o = $_;
2040                     $o =~ s/\.rc$/.res/; # Resource configuration
2041                     my $o = cleanfile($buildd, $o, $blddir);
2042                     $unified_info{sources}->{$ddest}->{$o} = -1;
2043                     $unified_info{sources}->{$o}->{$s} = -1;
2044                 } else {
2045                     $unified_info{sources}->{$ddest}->{$s} = 1;
2046                 }
2047             }
2048         }
2049
2050         foreach (keys %shared_sources) {
2051             my $dest = $_;
2052             my $ddest = cleanfile($buildd, $_, $blddir);
2053             if ($unified_info{rename}->{$ddest}) {
2054                 $ddest = $unified_info{rename}->{$ddest};
2055             }
2056             foreach (@{$shared_sources{$dest}}) {
2057                 my $s = cleanfile($sourced, $_, $blddir);
2058
2059                 # If it isn't in the source tree, we assume it's generated
2060                 # in the build tree
2061                 if ($s eq $src_configdata || ! -f $s || $generate{$_}) {
2062                     $s = cleanfile($buildd, $_, $blddir);
2063                 }
2064
2065                 if ($s =~ /\.(cc|cpp|c|s|S)$/) {
2066                     # We recognise C++, C and asm files
2067                     my $o = $_;
2068                     $o =~ s/\.[csS]$/.o/; # C and assembler
2069                     $o =~ s/\.(cc|cpp)$/_cc.o/; # C++
2070                     $o = cleanfile($buildd, $o, $blddir);
2071                     $unified_info{shared_sources}->{$ddest}->{$o} = -1;
2072                     $unified_info{sources}->{$o}->{$s} = -1;
2073                 } elsif ($s =~ /\.rc$/) {
2074                     # We also recognise resource files
2075                     my $o = $_;
2076                     $o =~ s/\.rc$/.res/; # Resource configuration
2077                     my $o = cleanfile($buildd, $o, $blddir);
2078                     $unified_info{shared_sources}->{$ddest}->{$o} = -1;
2079                     $unified_info{sources}->{$o}->{$s} = -1;
2080                 } elsif ($s =~ /\.ld$/) {
2081                     # We also recognise linker scripts (or corresponding)
2082                     # We know they are generated files
2083                     my $ld = cleanfile($buildd, $_, $blddir);
2084                     $unified_info{shared_sources}->{$ddest}->{$ld} = 1;
2085                 } else {
2086                     die "unrecognised source file type for shared library: $s\n";
2087                 }
2088             }
2089         }
2090
2091         foreach (keys %generate) {
2092             my $dest = $_;
2093             my $ddest = cleanfile($buildd, $_, $blddir);
2094             if ($unified_info{rename}->{$ddest}) {
2095                 $ddest = $unified_info{rename}->{$ddest};
2096             }
2097             die "more than one generator for $dest: "
2098                     ,join(" ", @{$generate{$_}}),"\n"
2099                     if scalar @{$generate{$_}} > 1;
2100             my @generator = split /\s+/, $generate{$dest}->[0];
2101             $generator[0] = cleanfile($sourced, $generator[0], $blddir),
2102             $unified_info{generate}->{$ddest} = [ @generator ];
2103         }
2104
2105         foreach (keys %depends) {
2106             my $dest = $_;
2107             my $ddest = $dest eq "" ? "" : cleanfile($sourced, $_, $blddir);
2108
2109             # If the destination doesn't exist in source, it can only be
2110             # a generated file in the build tree.
2111             if ($ddest ne "" && ($ddest eq $src_configdata || ! -f $ddest)) {
2112                 $ddest = cleanfile($buildd, $_, $blddir);
2113                 if ($unified_info{rename}->{$ddest}) {
2114                     $ddest = $unified_info{rename}->{$ddest};
2115                 }
2116             }
2117             foreach (@{$depends{$dest}}) {
2118                 my $d = cleanfile($sourced, $_, $blddir);
2119
2120                 # If we know it's generated, or assume it is because we can't
2121                 # find it in the source tree, we set file we depend on to be
2122                 # in the build tree rather than the source tree, and assume
2123                 # and that there are lines to build it in a BEGINRAW..ENDRAW
2124                 # section or in the Makefile template.
2125                 if ($d eq $src_configdata
2126                     || ! -f $d
2127                     || (grep { $d eq $_ }
2128                         map { cleanfile($srcdir, $_, $blddir) }
2129                         grep { /\.h$/ } keys %{$unified_info{generate}})) {
2130                     $d = cleanfile($buildd, $_, $blddir);
2131                 }
2132                 # Take note if the file to depend on is being renamed
2133                 # Take extra care with files ending with .a, they should
2134                 # be treated without that extension, and the extension
2135                 # should be added back after treatment.
2136                 $d =~ /(\.a)?$/;
2137                 my $e = $1 // "";
2138                 $d = $`;
2139                 if ($unified_info{rename}->{$d}) {
2140                     $d = $unified_info{rename}->{$d};
2141                 }
2142                 $d .= $e;
2143                 $unified_info{depends}->{$ddest}->{$d} = 1;
2144             }
2145         }
2146
2147         foreach (keys %includes) {
2148             my $dest = $_;
2149             my $ddest = cleanfile($sourced, $_, $blddir);
2150
2151             # If the destination doesn't exist in source, it can only be
2152             # a generated file in the build tree.
2153             if ($ddest eq $src_configdata || ! -f $ddest) {
2154                 $ddest = cleanfile($buildd, $_, $blddir);
2155                 if ($unified_info{rename}->{$ddest}) {
2156                     $ddest = $unified_info{rename}->{$ddest};
2157                 }
2158             }
2159             foreach (@{$includes{$dest}}) {
2160                 my $is = cleandir($sourced, $_, $blddir);
2161                 my $ib = cleandir($buildd, $_, $blddir);
2162                 push @{$unified_info{includes}->{$ddest}->{source}}, $is
2163                     unless grep { $_ eq $is } @{$unified_info{includes}->{$ddest}->{source}};
2164                 push @{$unified_info{includes}->{$ddest}->{build}}, $ib
2165                     unless grep { $_ eq $ib } @{$unified_info{includes}->{$ddest}->{build}};
2166             }
2167         }
2168
2169         foreach (keys %defines) {
2170             my $dest = $_;
2171             my $ddest = cleanfile($sourced, $_, $blddir);
2172
2173             # If the destination doesn't exist in source, it can only be
2174             # a generated file in the build tree.
2175             if (! -f $ddest) {
2176                 $ddest = cleanfile($buildd, $_, $blddir);
2177                 if ($unified_info{rename}->{$ddest}) {
2178                     $ddest = $unified_info{rename}->{$ddest};
2179                 }
2180             }
2181             foreach (@{$defines{$dest}}) {
2182                 m|^([^=]*)(=.*)?$|;
2183                 die "0 length macro name not permitted\n" if $1 eq "";
2184                 die "$1 defined more than once\n"
2185                     if defined $unified_info{defines}->{$ddest}->{$1};
2186                 $unified_info{defines}->{$ddest}->{$1} = $2;
2187             }
2188         }
2189     }
2190
2191     my $ordinals_text = join(', ', sort keys %ordinals);
2192     warn <<"EOF" if $ordinals_text;
2193
2194 WARNING: ORDINALS were specified for $ordinals_text
2195 They are ignored and should be replaced with a combination of GENERATE,
2196 DEPEND and SHARED_SOURCE.
2197 EOF
2198
2199     # Massage the result
2200
2201     # If we depend on a header file or a perl module, add an inclusion of
2202     # its directory to allow smoothe inclusion
2203     foreach my $dest (keys %{$unified_info{depends}}) {
2204         next if $dest eq "";
2205         foreach my $d (keys %{$unified_info{depends}->{$dest}}) {
2206             next unless $d =~ /\.(h|pm)$/;
2207             my $i = dirname($d);
2208             my $spot =
2209                 $d eq "configdata.pm" || defined($unified_info{generate}->{$d})
2210                 ? 'build' : 'source';
2211             push @{$unified_info{includes}->{$dest}->{$spot}}, $i
2212                 unless grep { $_ eq $i } @{$unified_info{includes}->{$dest}->{$spot}};
2213         }
2214     }
2215
2216     # Go through all intermediary files and change their names to something that
2217     # reflects what they will be built for.  Note that for some source files,
2218     # this leads to duplicate object files because they are used multiple times.
2219     # the goal is to rename all object files according to this scheme:
2220     #    {productname}-{midfix}-{origobjname}.[o|res]
2221     # the {midfix} is a keyword indicating the type of product, which is mostly
2222     # valuable for libraries since they come in two forms.
2223     #
2224     # This also reorganises the {sources} and {shared_sources} so that the
2225     # former only contains ALL object files that are supposed to end up in
2226     # static libraries and programs, while the latter contains ALL object files
2227     # that are supposed to end up in shared libraries and DSOs.
2228     # The main reason for having two different source structures is to allow
2229     # the same name to be used for the static and the shared variants of a
2230     # library.
2231     {
2232         # Take copies so we don't get interference from added stuff
2233         my %unified_copy = ();
2234         foreach (('sources', 'shared_sources')) {
2235             $unified_copy{$_} = { %{$unified_info{$_}} }
2236                 if defined($unified_info{$_});
2237             delete $unified_info{$_};
2238         }
2239         foreach my $prodtype (('programs', 'libraries', 'engines', 'scripts')) {
2240             # $intent serves multi purposes:
2241             # - give a prefix for the new object files names
2242             # - in the case of libraries, rearrange the object files so static
2243             #   libraries use the 'sources' structure exclusively, while shared
2244             #   libraries use the 'shared_sources' structure exclusively.
2245             my $intent = {
2246                 programs  => { bin    => { src => [ 'sources' ],
2247                                            dst => 'sources' } },
2248                 libraries => { lib    => { src => [ 'sources' ],
2249                                            dst => 'sources' },
2250                                shlib  => { prodselect =>
2251                                                sub { grep !/\.a$/, @_ },
2252                                            src => [ 'sources',
2253                                                     'shared_sources' ],
2254                                            dst => 'shared_sources' } },
2255                 engines   => { dso    => { src => [ 'sources',
2256                                                     'shared_sources' ],
2257                                            dst => 'shared_sources' } },
2258                 scripts   => { script => { src => [ 'sources' ],
2259                                            dst => 'sources' } }
2260                } -> {$prodtype};
2261             foreach my $kind (keys %$intent) {
2262                 next if ($intent->{$kind}->{dst} eq 'shared_sources'
2263                              && $disabled{shared});
2264
2265                 my @src = @{$intent->{$kind}->{src}};
2266                 my $dst = $intent->{$kind}->{dst};
2267                 my $prodselect = $intent->{$kind}->{prodselect} // sub { @_ };
2268                 foreach my $prod ($prodselect->(keys %{$unified_info{$prodtype}})) {
2269                     # %prod_sources has all applicable objects as keys, and
2270                     # their corresponding sources as values
2271                     my %prod_sources =
2272                         map { $_ => [ keys %{$unified_copy{sources}->{$_}} ] }
2273                         map { keys %{$unified_copy{$_}->{$prod}} }
2274                         @src;
2275                     foreach (keys %prod_sources) {
2276                         # Only affect object files and resource files,
2277                         # the others simply get a new value
2278                         # (+1 instead of -1)
2279                         if ($_ =~ /\.(o|res)$/) {
2280                             (my $prodname = $prod) =~ s|\.a$||;
2281                             my $newobj =
2282                                 catfile(dirname($_),
2283                                         basename($prodname)
2284                                             . '-' . $kind
2285                                             . '-' . basename($_));
2286                             $unified_info{$dst}->{$prod}->{$newobj} = 1;
2287                             foreach my $src (@{$prod_sources{$_}}) {
2288                                 $unified_info{sources}->{$newobj}->{$src} = 1;
2289                             }
2290                             # Adjust dependencies
2291                             foreach my $deps (keys %{$unified_info{depends}->{$_}}) {
2292                                 $unified_info{depends}->{$_}->{$deps} = -1;
2293                                 $unified_info{depends}->{$newobj}->{$deps} = 1;
2294                             }
2295                             # Adjust includes
2296                             foreach my $k (('source', 'build')) {
2297                                 next unless
2298                                     defined($unified_info{includes}->{$_}->{$k});
2299                                 my @incs = @{$unified_info{includes}->{$_}->{$k}};
2300                                 $unified_info{includes}->{$newobj}->{$k} = [ @incs ];
2301                             }
2302                         } else {
2303                             $unified_info{$dst}->{$prod}->{$_} = 1;
2304                         }
2305                     }
2306                 }
2307             }
2308         }
2309     }
2310     # At this point, we have a number of sources with the value -1.  They
2311     # aren't part of the local build and are probably meant for a different
2312     # platform, and can therefore be cleaned away.  That happens when making
2313     # %unified_info more efficient below.
2314
2315     ### Make unified_info a bit more efficient
2316     # One level structures
2317     foreach (("programs", "libraries", "engines", "scripts", "extra", "overrides")) {
2318         $unified_info{$_} = [ sort keys %{$unified_info{$_}} ];
2319     }
2320     # Two level structures
2321     foreach my $l1 (("install", "sources", "shared_sources", "ldadd", "depends")) {
2322         foreach my $l2 (sort keys %{$unified_info{$l1}}) {
2323             my @items =
2324                 sort
2325                 grep { $unified_info{$l1}->{$l2}->{$_} > 0 }
2326                 keys %{$unified_info{$l1}->{$l2}};
2327             if (@items) {
2328                 $unified_info{$l1}->{$l2} = [ @items ];
2329             } else {
2330                 delete $unified_info{$l1}->{$l2};
2331             }
2332         }
2333     }
2334     # Defines
2335     foreach my $dest (sort keys %{$unified_info{defines}}) {
2336         $unified_info{defines}->{$dest}
2337             = [ map { $_.$unified_info{defines}->{$dest}->{$_} }
2338                 sort keys %{$unified_info{defines}->{$dest}} ];
2339     }
2340     # Includes
2341     foreach my $dest (sort keys %{$unified_info{includes}}) {
2342         if (defined($unified_info{includes}->{$dest}->{build})) {
2343             my @source_includes = ();
2344             @source_includes = ( @{$unified_info{includes}->{$dest}->{source}} )
2345                 if defined($unified_info{includes}->{$dest}->{source});
2346             $unified_info{includes}->{$dest} =
2347                 [ @{$unified_info{includes}->{$dest}->{build}} ];
2348             foreach my $inc (@source_includes) {
2349                 push @{$unified_info{includes}->{$dest}}, $inc
2350                     unless grep { $_ eq $inc } @{$unified_info{includes}->{$dest}};
2351             }
2352         } elsif (defined($unified_info{includes}->{$dest}->{source})) {
2353             $unified_info{includes}->{$dest} =
2354                 [ @{$unified_info{includes}->{$dest}->{source}} ];
2355         } else {
2356             delete $unified_info{includes}->{$dest};
2357         }
2358     }
2359
2360     # For convenience collect information regarding directories where
2361     # files are generated, those generated files and the end product
2362     # they end up in where applicable.  Then, add build rules for those
2363     # directories
2364     my %loopinfo = ( "lib" => [ @{$unified_info{libraries}} ],
2365                      "dso" => [ @{$unified_info{engines}} ],
2366                      "bin" => [ @{$unified_info{programs}} ],
2367                      "script" => [ @{$unified_info{scripts}} ] );
2368     foreach my $type (keys %loopinfo) {
2369         foreach my $product (@{$loopinfo{$type}}) {
2370             my %dirs = ();
2371             my $pd = dirname($product);
2372
2373             foreach (@{$unified_info{sources}->{$product} // []},
2374                      @{$unified_info{shared_sources}->{$product} // []}) {
2375                 my $d = dirname($_);
2376
2377                 # We don't want to create targets for source directories
2378                 # when building out of source
2379                 next if ($config{sourcedir} ne $config{builddir}
2380                              && $d =~ m|^\Q$config{sourcedir}\E|);
2381                 # We already have a "test" target, and the current directory
2382                 # is just silly to make a target for
2383                 next if $d eq "test" || $d eq ".";
2384
2385                 $dirs{$d} = 1;
2386                 push @{$unified_info{dirinfo}->{$d}->{deps}}, $_
2387                     if $d ne $pd;
2388             }
2389             foreach (keys %dirs) {
2390                 push @{$unified_info{dirinfo}->{$_}->{products}->{$type}},
2391                     $product;
2392             }
2393         }
2394     }
2395 }
2396
2397 # For the schemes that need it, we provide the old *_obj configs
2398 # from the *_asm_obj ones
2399 foreach (grep /_(asm|aux)_src$/, keys %target) {
2400     my $src = $_;
2401     (my $obj = $_) =~ s/_(asm|aux)_src$/_obj/;
2402     $target{$obj} = $target{$src};
2403     $target{$obj} =~ s/\.[csS]\b/.o/g; # C and assembler
2404     $target{$obj} =~ s/\.(cc|cpp)\b/_cc.o/g; # C++
2405 }
2406
2407 # Write down our configuration where it fits #########################
2408
2409 print "Creating configdata.pm\n";
2410 open(OUT,">configdata.pm") || die "unable to create configdata.pm: $!\n";
2411 print OUT <<"EOF";
2412 #! $config{HASHBANGPERL}
2413
2414 package configdata;
2415
2416 use strict;
2417 use warnings;
2418
2419 use Exporter;
2420 #use vars qw(\@ISA \@EXPORT);
2421 our \@ISA = qw(Exporter);
2422 our \@EXPORT = qw(\%config \%target \%disabled \%withargs \%unified_info \@disablables);
2423
2424 EOF
2425 print OUT "our %config = (\n";
2426 foreach (sort keys %config) {
2427     if (ref($config{$_}) eq "ARRAY") {
2428         print OUT "  ", $_, " => [ ", join(", ",
2429                                            map { quotify("perl", $_) }
2430                                            @{$config{$_}}), " ],\n";
2431     } elsif (ref($config{$_}) eq "HASH") {
2432         print OUT "  ", $_, " => {";
2433         if (scalar keys %{$config{$_}} > 0) {
2434             print OUT "\n";
2435             foreach my $key (sort keys %{$config{$_}}) {
2436                 print OUT "      ",
2437                     join(" => ",
2438                          quotify("perl", $key),
2439                          defined $config{$_}->{$key}
2440                              ? quotify("perl", $config{$_}->{$key})
2441                              : "undef");
2442                 print OUT ",\n";
2443             }
2444             print OUT "  ";
2445         }
2446         print OUT "},\n";
2447     } else {
2448         print OUT "  ", $_, " => ", quotify("perl", $config{$_}), ",\n"
2449     }
2450 }
2451 print OUT <<"EOF";
2452 );
2453
2454 EOF
2455 print OUT "our %target = (\n";
2456 foreach (sort keys %target) {
2457     if (ref($target{$_}) eq "ARRAY") {
2458         print OUT "  ", $_, " => [ ", join(", ",
2459                                            map { quotify("perl", $_) }
2460                                            @{$target{$_}}), " ],\n";
2461     } else {
2462         print OUT "  ", $_, " => ", quotify("perl", $target{$_}), ",\n"
2463     }
2464 }
2465 print OUT <<"EOF";
2466 );
2467
2468 EOF
2469 print OUT "our \%available_protocols = (\n";
2470 print OUT "  tls => [ ", join(", ", map { quotify("perl", $_) } @tls), " ],\n";
2471 print OUT "  dtls => [ ", join(", ", map { quotify("perl", $_) } @dtls), " ],\n";
2472 print OUT <<"EOF";
2473 );
2474
2475 EOF
2476 print OUT "our \@disablables = (\n";
2477 foreach (@disablables) {
2478     print OUT "  ", quotify("perl", $_), ",\n";
2479 }
2480 print OUT <<"EOF";
2481 );
2482
2483 EOF
2484 print OUT "our \%disabled = (\n";
2485 foreach (sort keys %disabled) {
2486     print OUT "  ", quotify("perl", $_), " => ", quotify("perl", $disabled{$_}), ",\n";
2487 }
2488 print OUT <<"EOF";
2489 );
2490
2491 EOF
2492 print OUT "our %withargs = (\n";
2493 foreach (sort keys %withargs) {
2494     if (ref($withargs{$_}) eq "ARRAY") {
2495         print OUT "  ", $_, " => [ ", join(", ",
2496                                            map { quotify("perl", $_) }
2497                                            @{$withargs{$_}}), " ],\n";
2498     } else {
2499         print OUT "  ", $_, " => ", quotify("perl", $withargs{$_}), ",\n"
2500     }
2501 }
2502 print OUT <<"EOF";
2503 );
2504
2505 EOF
2506 if ($builder eq "unified") {
2507     my $recurse;
2508     $recurse = sub {
2509         my $indent = shift;
2510         foreach (@_) {
2511             if (ref $_ eq "ARRAY") {
2512                 print OUT " "x$indent, "[\n";
2513                 foreach (@$_) {
2514                     $recurse->($indent + 4, $_);
2515                 }
2516                 print OUT " "x$indent, "],\n";
2517             } elsif (ref $_ eq "HASH") {
2518                 my %h = %$_;
2519                 print OUT " "x$indent, "{\n";
2520                 foreach (sort keys %h) {
2521                     if (ref $h{$_} eq "") {
2522                         print OUT " "x($indent + 4), quotify("perl", $_), " => ", quotify("perl", $h{$_}), ",\n";
2523                     } else {
2524                         print OUT " "x($indent + 4), quotify("perl", $_), " =>\n";
2525                         $recurse->($indent + 8, $h{$_});
2526                     }
2527                 }
2528                 print OUT " "x$indent, "},\n";
2529             } else {
2530                 print OUT " "x$indent, quotify("perl", $_), ",\n";
2531             }
2532         }
2533     };
2534     print OUT "our %unified_info = (\n";
2535     foreach (sort keys %unified_info) {
2536         if (ref $unified_info{$_} eq "") {
2537             print OUT " "x4, quotify("perl", $_), " => ", quotify("perl", $unified_info{$_}), ",\n";
2538         } else {
2539             print OUT " "x4, quotify("perl", $_), " =>\n";
2540             $recurse->(8, $unified_info{$_});
2541         }
2542     }
2543     print OUT <<"EOF";
2544 );
2545
2546 EOF
2547 }
2548 print OUT
2549     "# The following data is only used when this files is use as a script\n";
2550 print OUT "my \@makevars = (\n";
2551 foreach (sort keys %user) {
2552     print OUT "    '",$_,"',\n";
2553 }
2554 print OUT ");\n";
2555 print OUT "my \%disabled_info = (\n";
2556 foreach my $what (sort keys %disabled_info) {
2557     print OUT "    '$what' => {\n";
2558     foreach my $info (sort keys %{$disabled_info{$what}}) {
2559         if (ref $disabled_info{$what}->{$info} eq 'ARRAY') {
2560             print OUT "        $info => [ ",
2561                 join(', ', map { "'$_'" } @{$disabled_info{$what}->{$info}}),
2562                 " ],\n";
2563         } else {
2564             print OUT "        $info => '", $disabled_info{$what}->{$info},
2565                 "',\n";
2566         }
2567     }
2568     print OUT "    },\n";
2569 }
2570 print OUT ");\n";
2571 print OUT 'my @user_crossable = qw( ', join (' ', @user_crossable), " );\n";
2572 print OUT << 'EOF';
2573 # If run directly, we can give some answers, and even reconfigure
2574 unless (caller) {
2575     use Getopt::Long;
2576     use File::Spec::Functions;
2577     use File::Basename;
2578     use Pod::Usage;
2579
2580     my $here = dirname($0);
2581
2582     my $dump = undef;
2583     my $cmdline = undef;
2584     my $options = undef;
2585     my $target = undef;
2586     my $envvars = undef;
2587     my $makevars = undef;
2588     my $buildparams = undef;
2589     my $reconf = undef;
2590     my $verbose = undef;
2591     my $help = undef;
2592     my $man = undef;
2593     GetOptions('dump|d'                 => \$dump,
2594                'command-line|c'         => \$cmdline,
2595                'options|o'              => \$options,
2596                'target|t'               => \$target,
2597                'environment|e'          => \$envvars,
2598                'make-variables|m'       => \$makevars,
2599                'build-parameters|b'     => \$buildparams,
2600                'reconfigure|reconf|r'   => \$reconf,
2601                'verbose|v'              => \$verbose,
2602                'help'                   => \$help,
2603                'man'                    => \$man)
2604         or die "Errors in command line arguments\n";
2605
2606     unless ($dump || $cmdline || $options || $target || $envvars || $makevars
2607             || $buildparams || $reconf || $verbose || $help || $man) {
2608         print STDERR <<"_____";
2609 You must give at least one option.
2610 For more information, do '$0 --help'
2611 _____
2612         exit(2);
2613     }
2614
2615     if ($help) {
2616         pod2usage(-exitval => 0,
2617                   -verbose => 1);
2618     }
2619     if ($man) {
2620         pod2usage(-exitval => 0,
2621                   -verbose => 2);
2622     }
2623     if ($dump || $cmdline) {
2624         print "\nCommand line (with current working directory = $here):\n\n";
2625         print '    ',join(' ',
2626                           $config{PERL},
2627                           catfile($config{sourcedir}, 'Configure'),
2628                           @{$config{perlargv}}), "\n";
2629         print "\nPerl information:\n\n";
2630         print '    ',$config{perl_cmd},"\n";
2631         print '    ',$config{perl_version},' for ',$config{perl_archname},"\n";
2632     }
2633     if ($dump || $options) {
2634         my $longest = 0;
2635         my $longest2 = 0;
2636         foreach my $what (@disablables) {
2637             $longest = length($what) if $longest < length($what);
2638             $longest2 = length($disabled{$what})
2639                 if $disabled{$what} && $longest2 < length($disabled{$what});
2640         }
2641         print "\nEnabled features:\n\n";
2642         foreach my $what (@disablables) {
2643             print "    $what\n" unless $disabled{$what};
2644         }
2645         print "\nDisabled features:\n\n";
2646         foreach my $what (@disablables) {
2647             if ($disabled{$what}) {
2648                 print "    $what", ' ' x ($longest - length($what) + 1),
2649                     "[$disabled{$what}]", ' ' x ($longest2 - length($disabled{$what}) + 1);
2650                 print $disabled_info{$what}->{macro}
2651                     if $disabled_info{$what}->{macro};
2652                 print ' (skip ',
2653                     join(', ', @{$disabled_info{$what}->{skipped}}),
2654                     ')'
2655                     if $disabled_info{$what}->{skipped};
2656                 print "\n";
2657             }
2658         }
2659     }
2660     if ($dump || $target) {
2661         print "\nConfig target attributes:\n\n";
2662         foreach (sort keys %target) {
2663             next if $_ =~ m|^_| || $_ eq 'template';
2664             my $quotify = sub {
2665                 map { (my $x = $_) =~ s|([\\\$\@"])|\\$1|g; "\"$x\""} @_;
2666             };
2667             print '    ', $_, ' => ';
2668             if (ref($target{$_}) eq "ARRAY") {
2669                 print '[ ', join(', ', $quotify->(@{$target{$_}})), " ],\n";
2670             } else {
2671                 print $quotify->($target{$_}), ",\n"
2672             }
2673         }
2674     }
2675     if ($dump || $envvars) {
2676         print "\nRecorded environment:\n\n";
2677         foreach (sort keys %{$config{perlenv}}) {
2678             print '    ',$_,' = ',($config{perlenv}->{$_} || ''),"\n";
2679         }
2680     }
2681     if ($dump || $makevars) {
2682         print "\nMakevars:\n\n";
2683         foreach my $var (@makevars) {
2684             my $prefix = '';
2685             $prefix = $config{CROSS_COMPILE}
2686                 if grep { $var eq $_ } @user_crossable;
2687             $prefix //= '';
2688             print '    ',$var,' ' x (16 - length $var),'= ',
2689                 (ref $config{$var} eq 'ARRAY'
2690                  ? join(' ', @{$config{$var}})
2691                  : $prefix.$config{$var}),
2692                 "\n"
2693                 if defined $config{$var};
2694         }
2695
2696         my @buildfile = ($config{builddir}, $config{build_file});
2697         unshift @buildfile, $here
2698             unless file_name_is_absolute($config{builddir});
2699         my $buildfile = canonpath(catdir(@buildfile));
2700         print <<"_____";
2701
2702 NOTE: These variables only represent the configuration view.  The build file
2703 template may have processed these variables further, please have a look at the
2704 build file for more exact data:
2705     $buildfile
2706 _____
2707     }
2708     if ($dump || $buildparams) {
2709         my @buildfile = ($config{builddir}, $config{build_file});
2710         unshift @buildfile, $here
2711             unless file_name_is_absolute($config{builddir});
2712         print "\nbuild file:\n\n";
2713         print "    ", canonpath(catfile(@buildfile)),"\n";
2714
2715         print "\nbuild file templates:\n\n";
2716         foreach (@{$config{build_file_templates}}) {
2717             my @tmpl = ($_);
2718             unshift @tmpl, $here
2719                 unless file_name_is_absolute($config{sourcedir});
2720             print '    ',canonpath(catfile(@tmpl)),"\n";
2721         }
2722     }
2723     if ($reconf) {
2724         if ($verbose) {
2725             print 'Reconfiguring with: ', join(' ',@{$config{perlargv}}), "\n";
2726             foreach (sort keys %{$config{perlenv}}) {
2727                 print '    ',$_,' = ',($config{perlenv}->{$_} || ""),"\n";
2728             }
2729         }
2730
2731         chdir $here;
2732         exec $^X,catfile($config{sourcedir}, 'Configure'),'reconf';
2733     }
2734 }
2735
2736 1;
2737
2738 __END__
2739
2740 =head1 NAME
2741
2742 configdata.pm - configuration data for OpenSSL builds
2743
2744 =head1 SYNOPSIS
2745
2746 Interactive:
2747
2748   perl configdata.pm [options]
2749
2750 As data bank module:
2751
2752   use configdata;
2753
2754 =head1 DESCRIPTION
2755
2756 This module can be used in two modes, interactively and as a module containing
2757 all the data recorded by OpenSSL's Configure script.
2758
2759 When used interactively, simply run it as any perl script, with at least one
2760 option, and you will get the information you ask for.  See L</OPTIONS> below.
2761
2762 When loaded as a module, you get a few databanks with useful information to
2763 perform build related tasks.  The databanks are:
2764
2765     %config             Configured things.
2766     %target             The OpenSSL config target with all inheritances
2767                         resolved.
2768     %disabled           The features that are disabled.
2769     @disablables        The list of features that can be disabled.
2770     %withargs           All data given through --with-THING options.
2771     %unified_info       All information that was computed from the build.info
2772                         files.
2773
2774 =head1 OPTIONS
2775
2776 =over 4
2777
2778 =item B<--help>
2779
2780 Print a brief help message and exit.
2781
2782 =item B<--man>
2783
2784 Print the manual page and exit.
2785
2786 =item B<--dump> | B<-d>
2787
2788 Print all relevant configuration data.  This is equivalent to B<--command-line>
2789 B<--options> B<--target> B<--environment> B<--make-variables>
2790 B<--build-parameters>.
2791
2792 =item B<--command-line> | B<-c>
2793
2794 Print the current configuration command line.
2795
2796 =item B<--options> | B<-o>
2797
2798 Print the features, both enabled and disabled, and display defined macro and
2799 skipped directories where applicable.
2800
2801 =item B<--target> | B<-t>
2802
2803 Print the config attributes for this config target.
2804
2805 =item B<--environment> | B<-e>
2806
2807 Print the environment variables and their values at the time of configuration.
2808
2809 =item B<--make-variables> | B<-m>
2810
2811 Print the main make variables generated in the current configuration
2812
2813 =item B<--build-parameters> | B<-b>
2814
2815 Print the build parameters, i.e. build file and build file templates.
2816
2817 =item B<--reconfigure> | B<--reconf> | B<-r>
2818
2819 Redo the configuration.
2820
2821 =item B<--verbose> | B<-v>
2822
2823 Verbose output.
2824
2825 =back
2826
2827 =cut
2828
2829 EOF
2830 close(OUT);
2831 if ($builder_platform eq 'unix') {
2832     my $mode = (0755 & ~umask);
2833     chmod $mode, 'configdata.pm'
2834         or warn sprintf("WARNING: Couldn't change mode for 'configdata.pm' to 0%03o: %s\n",$mode,$!);
2835 }
2836
2837 my %builders = (
2838     unified => sub {
2839         print 'Creating ',$target{build_file},"\n";
2840         run_dofile(catfile($blddir, $target{build_file}),
2841                    @{$config{build_file_templates}});
2842     },
2843     );
2844
2845 $builders{$builder}->($builder_platform, @builder_opts);
2846
2847 $SIG{__DIE__} = $orig_death_handler;
2848
2849 print <<"EOF" if ($disabled{threads} eq "unavailable");
2850
2851 The library could not be configured for supporting multi-threaded
2852 applications as the compiler options required on this system are not known.
2853 See file INSTALL for details if you need multi-threading.
2854 EOF
2855
2856 print <<"EOF" if ($no_shared_warn);
2857
2858 The options 'shared', 'pic' and 'dynamic-engine' aren't supported on this
2859 platform, so we will pretend you gave the option 'no-pic', which also disables
2860 'shared' and 'dynamic-engine'.  If you know how to implement shared libraries
2861 or position independent code, please let us know (but please first make sure
2862 you have tried with a current version of OpenSSL).
2863 EOF
2864
2865 print <<"EOF";
2866
2867 **********************************************************************
2868 ***                                                                ***
2869 ***   OpenSSL has been successfully configured                     ***
2870 ***                                                                ***
2871 ***   If you encounter a problem while building, please open an    ***
2872 ***   issue on GitHub <https://github.com/openssl/openssl/issues>  ***
2873 ***   and include the output from the following command:           ***
2874 ***                                                                ***
2875 ***       perl configdata.pm --dump                                ***
2876 ***                                                                ***
2877 ***   (If you are new to OpenSSL, you might want to consult the    ***
2878 ***   'Troubleshooting' section in the INSTALL file first)         ***
2879 ***                                                                ***
2880 **********************************************************************
2881 EOF
2882
2883 exit(0);
2884
2885 ######################################################################
2886 #
2887 # Helpers and utility functions
2888 #
2889
2890 # Death handler, to print a helpful message in case of failure #######
2891 #
2892 sub death_handler {
2893     die @_ if $^S;              # To prevent the added message in eval blocks
2894     my $build_file = $target{build_file} // "build file";
2895     my @message = ( <<"_____", @_ );
2896
2897 Failure!  $build_file wasn't produced.
2898 Please read INSTALL and associated NOTES files.  You may also have to look over
2899 your available compiler tool chain or change your configuration.
2900
2901 _____
2902
2903     # Dying is terminal, so it's ok to reset the signal handler here.
2904     $SIG{__DIE__} = $orig_death_handler;
2905     die @message;
2906 }
2907
2908 # Configuration file reading #########################################
2909
2910 # Note: All of the helper functions are for lazy evaluation.  They all
2911 # return a CODE ref, which will return the intended value when evaluated.
2912 # Thus, whenever there's mention of a returned value, it's about that
2913 # intended value.
2914
2915 # Helper function to implement conditional inheritance depending on the
2916 # value of $disabled{asm}.  Used in inherit_from values as follows:
2917 #
2918 #      inherit_from => [ "template", asm("asm_tmpl") ]
2919 #
2920 sub asm {
2921     my @x = @_;
2922     sub {
2923         $disabled{asm} ? () : @x;
2924     }
2925 }
2926
2927 # Helper function to implement conditional value variants, with a default
2928 # plus additional values based on the value of $config{build_type}.
2929 # Arguments are given in hash table form:
2930 #
2931 #       picker(default => "Basic string: ",
2932 #              debug   => "debug",
2933 #              release => "release")
2934 #
2935 # When configuring with --debug, the resulting string will be
2936 # "Basic string: debug", and when not, it will be "Basic string: release"
2937 #
2938 # This can be used to create variants of sets of flags according to the
2939 # build type:
2940 #
2941 #       cflags => picker(default => "-Wall",
2942 #                        debug   => "-g -O0",
2943 #                        release => "-O3")
2944 #
2945 sub picker {
2946     my %opts = @_;
2947     return sub { add($opts{default} || (),
2948                      $opts{$config{build_type}} || ())->(); }
2949 }
2950
2951 # Helper function to combine several values of different types into one.
2952 # This is useful if you want to combine a string with the result of a
2953 # lazy function, such as:
2954 #
2955 #       cflags => combine("-Wall", sub { $disabled{zlib} ? () : "-DZLIB" })
2956 #
2957 sub combine {
2958     my @stuff = @_;
2959     return sub { add(@stuff)->(); }
2960 }
2961
2962 # Helper function to implement conditional values depending on the value
2963 # of $disabled{threads}.  Can be used as follows:
2964 #
2965 #       cflags => combine("-Wall", threads("-pthread"))
2966 #
2967 sub threads {
2968     my @flags = @_;
2969     return sub { add($disabled{threads} ? () : @flags)->(); }
2970 }
2971
2972 sub shared {
2973     my @flags = @_;
2974     return sub { add($disabled{shared} ? () : @flags)->(); }
2975 }
2976
2977 our $add_called = 0;
2978 # Helper function to implement adding values to already existing configuration
2979 # values.  It handles elements that are ARRAYs, CODEs and scalars
2980 sub _add {
2981     my $separator = shift;
2982
2983     # If there's any ARRAY in the collection of values OR the separator
2984     # is undef, we will return an ARRAY of combined values, otherwise a
2985     # string of joined values with $separator as the separator.
2986     my $found_array = !defined($separator);
2987
2988     my @values =
2989         map {
2990             my $res = $_;
2991             while (ref($res) eq "CODE") {
2992                 $res = $res->();
2993             }
2994             if (defined($res)) {
2995                 if (ref($res) eq "ARRAY") {
2996                     $found_array = 1;
2997                     @$res;
2998                 } else {
2999                     $res;
3000                 }
3001             } else {
3002                 ();
3003             }
3004     } (@_);
3005
3006     $add_called = 1;
3007
3008     if ($found_array) {
3009         [ @values ];
3010     } else {
3011         join($separator, grep { defined($_) && $_ ne "" } @values);
3012     }
3013 }
3014 sub add_before {
3015     my $separator = " ";
3016     if (ref($_[$#_]) eq "HASH") {
3017         my $opts = pop;
3018         $separator = $opts->{separator};
3019     }
3020     my @x = @_;
3021     sub { _add($separator, @x, @_) };
3022 }
3023 sub add {
3024     my $separator = " ";
3025     if (ref($_[$#_]) eq "HASH") {
3026         my $opts = pop;
3027         $separator = $opts->{separator};
3028     }
3029     my @x = @_;
3030     sub { _add($separator, @_, @x) };
3031 }
3032
3033 sub read_eval_file {
3034     my $fname = shift;
3035     my $content;
3036     my @result;
3037
3038     open F, "< $fname" or die "Can't open '$fname': $!\n";
3039     {
3040         undef local $/;
3041         $content = <F>;
3042     }
3043     close F;
3044     {
3045         local $@;
3046
3047         @result = ( eval $content );
3048         warn $@ if $@;
3049     }
3050     return wantarray ? @result : $result[0];
3051 }
3052
3053 # configuration reader, evaluates the input file as a perl script and expects
3054 # it to fill %targets with target configurations.  Those are then added to
3055 # %table.
3056 sub read_config {
3057     my $fname = shift;
3058     my %targets;
3059
3060     {
3061         # Protect certain tables from tampering
3062         local %table = ();
3063
3064         %targets = read_eval_file($fname);
3065     }
3066     my %preexisting = ();
3067     foreach (sort keys %targets) {
3068         $preexisting{$_} = 1 if $table{$_};
3069     }
3070     die <<"EOF",
3071 The following config targets from $fname
3072 shadow pre-existing config targets with the same name:
3073 EOF
3074         map { "  $_\n" } sort keys %preexisting
3075         if %preexisting;
3076
3077
3078     # For each target, check that it's configured with a hash table.
3079     foreach (keys %targets) {
3080         if (ref($targets{$_}) ne "HASH") {
3081             if (ref($targets{$_}) eq "") {
3082                 warn "Deprecated target configuration for $_, ignoring...\n";
3083             } else {
3084                 warn "Misconfigured target configuration for $_ (should be a hash table), ignoring...\n";
3085             }
3086             delete $targets{$_};
3087         } else {
3088             $targets{$_}->{_conf_fname_int} = add([ $fname ]);
3089         }
3090     }
3091
3092     %table = (%table, %targets);
3093
3094 }
3095
3096 # configuration resolver.  Will only resolve all the lazy evaluation
3097 # codeblocks for the chosen target and all those it inherits from,
3098 # recursively
3099 sub resolve_config {
3100     my $target = shift;
3101     my @breadcrumbs = @_;
3102
3103 #    my $extra_checks = defined($ENV{CONFIGURE_EXTRA_CHECKS});
3104
3105     if (grep { $_ eq $target } @breadcrumbs) {
3106         die "inherit_from loop!  target backtrace:\n  "
3107             ,$target,"\n  ",join("\n  ", @breadcrumbs),"\n";
3108     }
3109
3110     if (!defined($table{$target})) {
3111         warn "Warning! target $target doesn't exist!\n";
3112         return ();
3113     }
3114     # Recurse through all inheritances.  They will be resolved on the
3115     # fly, so when this operation is done, they will all just be a
3116     # bunch of attributes with string values.
3117     # What we get here, though, are keys with references to lists of
3118     # the combined values of them all.  We will deal with lists after
3119     # this stage is done.
3120     my %combined_inheritance = ();
3121     if ($table{$target}->{inherit_from}) {
3122         my @inherit_from =
3123             map { ref($_) eq "CODE" ? $_->() : $_ } @{$table{$target}->{inherit_from}};
3124         foreach (@inherit_from) {
3125             my %inherited_config = resolve_config($_, $target, @breadcrumbs);
3126
3127             # 'template' is a marker that's considered private to
3128             # the config that had it.
3129             delete $inherited_config{template};
3130
3131             foreach (keys %inherited_config) {
3132                 if (!$combined_inheritance{$_}) {
3133                     $combined_inheritance{$_} = [];
3134                 }
3135                 push @{$combined_inheritance{$_}}, $inherited_config{$_};
3136             }
3137         }
3138     }
3139
3140     # We won't need inherit_from in this target any more, since we've
3141     # resolved all the inheritances that lead to this
3142     delete $table{$target}->{inherit_from};
3143
3144     # Now is the time to deal with those lists.  Here's the place to
3145     # decide what shall be done with those lists, all based on the
3146     # values of the target we're currently dealing with.
3147     # - If a value is a coderef, it will be executed with the list of
3148     #   inherited values as arguments.
3149     # - If the corresponding key doesn't have a value at all or is the
3150     #   empty string, the inherited value list will be run through the
3151     #   default combiner (below), and the result becomes this target's
3152     #   value.
3153     # - Otherwise, this target's value is assumed to be a string that
3154     #   will simply override the inherited list of values.
3155     my $default_combiner = add();
3156
3157     my %all_keys =
3158         map { $_ => 1 } (keys %combined_inheritance,
3159                          keys %{$table{$target}});
3160
3161     sub process_values {
3162         my $object    = shift;
3163         my $inherited = shift;  # Always a [ list ]
3164         my $target    = shift;
3165         my $entry     = shift;
3166
3167         $add_called = 0;
3168
3169         while(ref($object) eq "CODE") {
3170             $object = $object->(@$inherited);
3171         }
3172         if (!defined($object)) {
3173             return ();
3174         }
3175         elsif (ref($object) eq "ARRAY") {
3176             local $add_called;  # To make sure recursive calls don't affect it
3177             return [ map { process_values($_, $inherited, $target, $entry) }
3178                      @$object ];
3179         } elsif (ref($object) eq "") {
3180             return $object;
3181         } else {
3182             die "cannot handle reference type ",ref($object)
3183                 ," found in target ",$target," -> ",$entry,"\n";
3184         }
3185     }
3186
3187     foreach (sort keys %all_keys) {
3188         my $previous = $combined_inheritance{$_};
3189
3190         # Current target doesn't have a value for the current key?
3191         # Assign it the default combiner, the rest of this loop body
3192         # will handle it just like any other coderef.
3193         if (!exists $table{$target}->{$_}) {
3194             $table{$target}->{$_} = $default_combiner;
3195         }
3196
3197         $table{$target}->{$_} = process_values($table{$target}->{$_},
3198                                                $combined_inheritance{$_},
3199                                                $target, $_);
3200         unless(defined($table{$target}->{$_})) {
3201             delete $table{$target}->{$_};
3202         }
3203 #        if ($extra_checks &&
3204 #            $previous && !($add_called ||  $previous ~~ $table{$target}->{$_})) {
3205 #            warn "$_ got replaced in $target\n";
3206 #        }
3207     }
3208
3209     # Finally done, return the result.
3210     return %{$table{$target}};
3211 }
3212
3213 sub usage
3214         {
3215         print STDERR $usage;
3216         print STDERR "\npick os/compiler from:\n";
3217         my $j=0;
3218         my $i;
3219         my $k=0;
3220         foreach $i (sort keys %table)
3221                 {
3222                 next if $table{$i}->{template};
3223                 next if $i =~ /^debug/;
3224                 $k += length($i) + 1;
3225                 if ($k > 78)
3226                         {
3227                         print STDERR "\n";
3228                         $k=length($i);
3229                         }
3230                 print STDERR $i . " ";
3231                 }
3232         foreach $i (sort keys %table)
3233                 {
3234                 next if $table{$i}->{template};
3235                 next if $i !~ /^debug/;
3236                 $k += length($i) + 1;
3237                 if ($k > 78)
3238                         {
3239                         print STDERR "\n";
3240                         $k=length($i);
3241                         }
3242                 print STDERR $i . " ";
3243                 }
3244         print STDERR "\n\nNOTE: If in doubt, on Unix-ish systems use './config'.\n";
3245         exit(1);
3246         }
3247
3248 sub run_dofile
3249 {
3250     my $out = shift;
3251     my @templates = @_;
3252
3253     unlink $out || warn "Can't remove $out, $!"
3254         if -f $out;
3255     foreach (@templates) {
3256         die "Can't open $_, $!" unless -f $_;
3257     }
3258     my $perlcmd = (quotify("maybeshell", $config{PERL}))[0];
3259     my $cmd = "$perlcmd \"-I.\" \"-Mconfigdata\" \"$dofile\" -o\"Configure\" \"".join("\" \"",@templates)."\" > \"$out.new\"";
3260     #print STDERR "DEBUG[run_dofile]: \$cmd = $cmd\n";
3261     system($cmd);
3262     exit 1 if $? != 0;
3263     rename("$out.new", $out) || die "Can't rename $out.new, $!";
3264 }
3265
3266 sub compiler_predefined {
3267     state %predefined;
3268     my $cc = shift;
3269
3270     return () if $^O eq 'VMS';
3271
3272     die 'compiler_predefined called without a compiler command'
3273         unless $cc;
3274
3275     if (! $predefined{$cc}) {
3276
3277         $predefined{$cc} = {};
3278
3279         # collect compiler pre-defines from gcc or gcc-alike...
3280         open(PIPE, "$cc -dM -E -x c /dev/null 2>&1 |");
3281         while (my $l = <PIPE>) {
3282             $l =~ m/^#define\s+(\w+(?:\(\w+\))?)(?:\s+(.+))?/ or last;
3283             $predefined{$cc}->{$1} = $2 // '';
3284         }
3285         close(PIPE);
3286     }
3287
3288     return %{$predefined{$cc}};
3289 }
3290
3291 sub which
3292 {
3293     my ($name)=@_;
3294
3295     if (eval { require IPC::Cmd; 1; }) {
3296         IPC::Cmd->import();
3297         return scalar IPC::Cmd::can_run($name);
3298     } else {
3299         # if there is $directories component in splitpath,
3300         # then it's not something to test with $PATH...
3301         return $name if (File::Spec->splitpath($name))[1];
3302
3303         foreach (File::Spec->path()) {
3304             my $fullpath = catfile($_, "$name$target{exe_extension}");
3305             if (-f $fullpath and -x $fullpath) {
3306                 return $fullpath;
3307             }
3308         }
3309     }
3310 }
3311
3312 sub env
3313 {
3314     my $name = shift;
3315     my %opts = @_;
3316
3317     unless ($opts{cacheonly}) {
3318         # Note that if $ENV{$name} doesn't exist or is undefined,
3319         # $config{perlenv}->{$name} will be created with the value
3320         # undef.  This is intentional.
3321
3322         $config{perlenv}->{$name} = $ENV{$name}
3323             if ! exists $config{perlenv}->{$name};
3324     }
3325     return $config{perlenv}->{$name};
3326 }
3327
3328 # Configuration printer ##############################################
3329
3330 sub print_table_entry
3331 {
3332     local $now_printing = shift;
3333     my %target = resolve_config($now_printing);
3334     my $type = shift;
3335
3336     # Don't print the templates
3337     return if $target{template};
3338
3339     my @sequence = (
3340         "sys_id",
3341         "cpp",
3342         "cppflags",
3343         "defines",
3344         "includes",
3345         "cc",
3346         "cflags",
3347         "unistd",
3348         "ld",
3349         "lflags",
3350         "loutflag",
3351         "ex_libs",
3352         "bn_ops",
3353         "apps_aux_src",
3354         "cpuid_asm_src",
3355         "uplink_aux_src",
3356         "bn_asm_src",
3357         "ec_asm_src",
3358         "des_asm_src",
3359         "aes_asm_src",
3360         "bf_asm_src",
3361         "md5_asm_src",
3362         "cast_asm_src",
3363         "sha1_asm_src",
3364         "rc4_asm_src",
3365         "rmd160_asm_src",
3366         "rc5_asm_src",
3367         "wp_asm_src",
3368         "cmll_asm_src",
3369         "modes_asm_src",
3370         "padlock_asm_src",
3371         "chacha_asm_src",
3372         "poly1035_asm_src",
3373         "thread_scheme",
3374         "perlasm_scheme",
3375         "dso_scheme",
3376         "shared_target",
3377         "shared_cflag",
3378         "shared_defines",
3379         "shared_ldflag",
3380         "shared_rcflag",
3381         "shared_extension",
3382         "dso_extension",
3383         "obj_extension",
3384         "exe_extension",
3385         "ranlib",
3386         "ar",
3387         "arflags",
3388         "aroutflag",
3389         "rc",
3390         "rcflags",
3391         "rcoutflag",
3392         "mt",
3393         "mtflags",
3394         "mtinflag",
3395         "mtoutflag",
3396         "multilib",
3397         "build_scheme",
3398         );
3399
3400     if ($type eq "TABLE") {
3401         print "\n";
3402         print "*** $now_printing\n";
3403         foreach (@sequence) {
3404             if (ref($target{$_}) eq "ARRAY") {
3405                 printf "\$%-12s = %s\n", $_, join(" ", @{$target{$_}});
3406             } else {
3407                 printf "\$%-12s = %s\n", $_, $target{$_};
3408             }
3409         }
3410     } elsif ($type eq "HASH") {
3411         my $largest =
3412             length((sort { length($a) <=> length($b) } @sequence)[-1]);
3413         print "    '$now_printing' => {\n";
3414         foreach (@sequence) {
3415             if ($target{$_}) {
3416                 if (ref($target{$_}) eq "ARRAY") {
3417                     print "      '",$_,"'"," " x ($largest - length($_))," => [ ",join(", ", map { "'$_'" } @{$target{$_}})," ],\n";
3418                 } else {
3419                     print "      '",$_,"'"," " x ($largest - length($_))," => '",$target{$_},"',\n";
3420                 }
3421             }
3422         }
3423         print "    },\n";
3424     }
3425 }
3426
3427 # Utility routines ###################################################
3428
3429 # On VMS, if the given file is a logical name, File::Spec::Functions
3430 # will consider it an absolute path.  There are cases when we want a
3431 # purely syntactic check without checking the environment.
3432 sub isabsolute {
3433     my $file = shift;
3434
3435     # On non-platforms, we just use file_name_is_absolute().
3436     return file_name_is_absolute($file) unless $^O eq "VMS";
3437
3438     # If the file spec includes a device or a directory spec,
3439     # file_name_is_absolute() is perfectly safe.
3440     return file_name_is_absolute($file) if $file =~ m|[:\[]|;
3441
3442     # Here, we know the given file spec isn't absolute
3443     return 0;
3444 }
3445
3446 # Makes a directory absolute and cleans out /../ in paths like foo/../bar
3447 # On some platforms, this uses rel2abs(), while on others, realpath() is used.
3448 # realpath() requires that at least all path components except the last is an
3449 # existing directory.  On VMS, the last component of the directory spec must
3450 # exist.
3451 sub absolutedir {
3452     my $dir = shift;
3453
3454     # realpath() is quite buggy on VMS.  It uses LIB$FID_TO_NAME, which
3455     # will return the volume name for the device, no matter what.  Also,
3456     # it will return an incorrect directory spec if the argument is a
3457     # directory that doesn't exist.
3458     if ($^O eq "VMS") {
3459         return rel2abs($dir);
3460     }
3461
3462     # We use realpath() on Unix, since no other will properly clean out
3463     # a directory spec.
3464     use Cwd qw/realpath/;
3465
3466     return realpath($dir);
3467 }
3468
3469 sub quotify {
3470     my %processors = (
3471         perl    => sub { my $x = shift;
3472                          $x =~ s/([\\\$\@"])/\\$1/g;
3473                          return '"'.$x.'"'; },
3474         maybeshell => sub { my $x = shift;
3475                             (my $y = $x) =~ s/([\\\"])/\\$1/g;
3476                             if ($x ne $y || $x =~ m|\s|) {
3477                                 return '"'.$y.'"';
3478                             } else {
3479                                 return $x;
3480                             }
3481                         },
3482         );
3483     my $for = shift;
3484     my $processor =
3485         defined($processors{$for}) ? $processors{$for} : sub { shift; };
3486
3487     return map { $processor->($_); } @_;
3488 }
3489
3490 # collect_from_file($filename, $line_concat_cond_re, $line_concat)
3491 # $filename is a file name to read from
3492 # $line_concat_cond_re is a regexp detecting a line continuation ending
3493 # $line_concat is a CODEref that takes care of concatenating two lines
3494 sub collect_from_file {
3495     my $filename = shift;
3496     my $line_concat_cond_re = shift;
3497     my $line_concat = shift;
3498
3499     open my $fh, $filename || die "unable to read $filename: $!\n";
3500     return sub {
3501         my $saved_line = "";
3502         $_ = "";
3503         while (<$fh>) {
3504             s|\R$||;
3505             if (defined $line_concat) {
3506                 $_ = $line_concat->($saved_line, $_);
3507                 $saved_line = "";
3508             }
3509             if (defined $line_concat_cond_re && /$line_concat_cond_re/) {
3510                 $saved_line = $_;
3511                 next;
3512             }
3513             return $_;
3514         }
3515         die "$filename ending with continuation line\n" if $_;
3516         close $fh;
3517         return undef;
3518     }
3519 }
3520
3521 # collect_from_array($array, $line_concat_cond_re, $line_concat)
3522 # $array is an ARRAYref of lines
3523 # $line_concat_cond_re is a regexp detecting a line continuation ending
3524 # $line_concat is a CODEref that takes care of concatenating two lines
3525 sub collect_from_array {
3526     my $array = shift;
3527     my $line_concat_cond_re = shift;
3528     my $line_concat = shift;
3529     my @array = (@$array);
3530
3531     return sub {
3532         my $saved_line = "";
3533         $_ = "";
3534         while (defined($_ = shift @array)) {
3535             s|\R$||;
3536             if (defined $line_concat) {
3537                 $_ = $line_concat->($saved_line, $_);
3538                 $saved_line = "";
3539             }
3540             if (defined $line_concat_cond_re && /$line_concat_cond_re/) {
3541                 $saved_line = $_;
3542                 next;
3543             }
3544             return $_;
3545         }
3546         die "input text ending with continuation line\n" if $_;
3547         return undef;
3548     }
3549 }
3550
3551 # collect_information($lineiterator, $line_continue, $regexp => $CODEref, ...)
3552 # $lineiterator is a CODEref that delivers one line at a time.
3553 # All following arguments are regex/CODEref pairs, where the regexp detects a
3554 # line and the CODEref does something with the result of the regexp.
3555 sub collect_information {
3556     my $lineiterator = shift;
3557     my %collectors = @_;
3558
3559     while(defined($_ = $lineiterator->())) {
3560         s|\R$||;
3561         my $found = 0;
3562         if ($collectors{"BEFORE"}) {
3563             $collectors{"BEFORE"}->($_);
3564         }
3565         foreach my $re (keys %collectors) {
3566             if ($re !~ /^OTHERWISE|BEFORE|AFTER$/ && /$re/) {
3567                 $collectors{$re}->($lineiterator);
3568                 $found = 1;
3569             };
3570         }
3571         if ($collectors{"OTHERWISE"}) {
3572             $collectors{"OTHERWISE"}->($lineiterator, $_)
3573                 unless $found || !defined $collectors{"OTHERWISE"};
3574         }
3575         if ($collectors{"AFTER"}) {
3576             $collectors{"AFTER"}->($_);
3577         }
3578     }
3579 }
3580
3581 # tokenize($line)
3582 # $line is a line of text to split up into tokens
3583 # returns a list of tokens
3584 #
3585 # Tokens are divided by spaces.  If the tokens include spaces, they
3586 # have to be quoted with single or double quotes.  Double quotes
3587 # inside a double quoted token must be escaped.  Escaping is done
3588 # with backslash.
3589 # Basically, the same quoting rules apply for " and ' as in any
3590 # Unix shell.
3591 sub tokenize {
3592     my $line = my $debug_line = shift;
3593     my @result = ();
3594
3595     while ($line =~ s|^\s+||, $line ne "") {
3596         my $token = "";
3597         while ($line ne "" && $line !~ m|^\s|) {
3598             if ($line =~ m/^"((?:[^"\\]+|\\.)*)"/) {
3599                 $token .= $1;
3600                 $line = $';
3601             } elsif ($line =~ m/^'([^']*)'/) {
3602                 $token .= $1;
3603                 $line = $';
3604             } elsif ($line =~ m/^(\S+)/) {
3605                 $token .= $1;
3606                 $line = $';
3607             }
3608         }
3609         push @result, $token;
3610     }
3611
3612     if ($ENV{CONFIGURE_DEBUG_TOKENIZE}) {
3613         print STDERR "DEBUG[tokenize]: Parsed '$debug_line' into:\n";
3614         print STDERR "DEBUG[tokenize]: ('", join("', '", @result), "')\n";
3615     }
3616     return @result;
3617 }