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