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